2017-03-03 66 views
9
type someType = { 
    keyOne: string, 
    keyTwo: string, 
}; 

type someOtherType = { 
    keyOne: string, 
    keyTwo: string, 
    keyThree: string, 
}; 

这些类型的两个创建的流类型是包含keyOnekeyTwo,唯一的区别是后者延伸前者与keyThree额外密钥对象。流速:由延伸的另一类型

而不是编写重复代码,是否可以通过扩展someType来构建someOtherType流类型?在我看来,ES6对象休息/传播浮现在脑海,但我不知道如何在Flow中完成这样的事情。

谢谢!

+1

的可能的复制[流动型:类型继承(A类型是B型的一个子集...)](http://stackoverflow.com/questions/42281539/flowtype-in​​heritance-of-types- type-a-is-a-subset-of-b) –

+0

很酷,感谢您的链接。 –

回答

10

你在找什么是intersection type。根据文档:

交集类型要求值为所有输入类型。

语法:路口:<类型1> & <类型2> ... & <键入n>

交叉型旨在扩展现有类型和添加其他类型的要求给它。

type someType = { 
    keyOne: string, 
    keyTwo: string 
} 

type someOtherType = someType & { 
    keyThree: string 
} 

const shouldBeOk: someOtherType = { 
    keyOne: 'biz', 
    keyTwo: 'buzz', 
    keyThree: 'baz', 
} 

const shouldError: someOtherType = { 
    keyOne: 123, 
    keyTwo: 'hello', 
    keyThree: 'world', 
} 

// flow error: 
16: const shouldError: someOtherType = { 
          ^object literal. This type is incompatible with 
8: type someOtherType = someType & { 
         ^object type 

交点类型的逻辑反义词是union type。根据文档:

联合类型要求值为输入类型之一。

语法:Union:< type 1> | <类型2> ... | <类型n>

作为一个例子。您可以使用联合类型来创建一个枚举类型。

type fooBarBazType = 'foo' | 'bar' | 'baz'; 
const shouldBeOk: fooBarBazType = 'bar'; 

const shouldError: fooBarBazType = 'buzz'; 

4: const shouldError: fooBarBazType = 'buzz'; 
            ^string. This type is incompatible with 
4: const shouldError: fooBarBazType = 'buzz'; 
        ^string enum 
+1

上述“可能重复”的答案已过时。相交类型[自2016年7月1日起实施](https://flowtype.org/blog/2016/07/01/New-Unions-Intersections.html)。 – thejohnbackes

+0

这不是过时的。在我的回答中,我提到交集类型。他们确实适用于大多数情况。但是,它们会导致出现奇怪的错误消息,并且在某些情况下它们不能按预期工作(例如,使用确切类型)。对象类型传播将更好地实现此目的,事实上它只是在昨天登陆:https://github.com/facebook/flow/commit/ad443dc92879ae21705d4c61b942ba2f8ad61e4d –

+0

对不起Nat,我误解了。我以为你在说交叉口类型还没有发布。 – thejohnbackes