流程:通过扩展另一种类型来创建流类型 [英] Flow: Create a flow type by extending another type
问题描述
type someType = {
keyOne: string,
keyTwo: string,
};
type someOtherType = {
keyOne: string,
keyTwo: string,
keyThree: string,
};
这两种类型的对象都包含 keyOne
和 keyTwo
,唯一的区别是后者 extends 前者的附加键 keyThree
。
Both of these types are objects that contain keyOne
and keyTwo
, the only difference is the latter extends the former with an additional key of keyThree
.
不是编写重复的代码,而是可以通过扩展<$来构建 someOtherType
流类型C $ C> SOMETYPE ?在我看来,我想到了ES6对象休息/传播,但我不确定如何在Flow中完成这样的事情。
Rather than writing duplicated code, is it possible to build the someOtherType
flow type by extending someType
? In my mind, ES6 object rest/spread comes to mind, but I'm not sure how to accomplish something like this in Flow.
谢谢!
推荐答案
您正在寻找的是交叉点类型。根据文档:
What you're looking for is the intersection type. According to the documentation:
交集类型需要一个值作为所有输入类型。
An intersection type requires a value to be all of the input types.
语法:Intersection:< 1型>& < 2型> ...& <类型n>
Syntax: Intersection: < type 1 > & < type 2 > ... & < type n >
交集类型旨在扩展现有类型并向其添加其他类型要求。
The intersection type is intended to extend an existing type and add additional type requirements to it.
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
交叉点类型的逻辑相反是联合类型。根据文档:
The logical opposite of the intersection type is the union type. According to the documentation:
联合类型要求值为输入类型之一。
A union type requires for a value to be one of the input types.
语法:Union:<类型1> | < 2型> ... | < type n>
Syntax: Union: < type 1 > | < type 2 > ... | < type n >
举个例子。你可以使用union类型来创建一个可枚举的。
As an example. you can use the union type to create an enumerable.
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
这篇关于流程:通过扩展另一种类型来创建流类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!