Jon*_*rsi 21 javascript casting type-conversion flowtype
type someType = {
keyOne: string,
keyTwo: string,
};
type someOtherType = {
keyOne: string,
keyTwo: string,
keyThree: string,
};
Run Code Online (Sandbox Code Playgroud)
这两种类型都是包含keyOne和的对象,keyTwo唯一的区别是后者用附加键扩展前者keyThree.
而不是编写重复的代码,是否可以someOtherType通过扩展来构建流类型someType?在我看来,我想到了ES6对象休息/传播,但我不确定如何在Flow中完成这样的事情.
谢谢!
the*_*kes 27
您正在寻找的是交叉类型.根据文件:
交集类型要求值为所有输入类型.
语法:Intersection:<type 1>&<type 2> ...&<type 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
Run Code Online (Sandbox Code Playgroud)
交集类型的逻辑相反的是联合类型.根据文件:
联合类型要求值为输入类型之一.
语法:Union:<type 1> | <类型2> ... | <type n>
举个例子.您可以使用union类型来创建可枚举.
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
Run Code Online (Sandbox Code Playgroud)
she*_*hem 18
对不起,接受的答案是错误的,它的工作只是因为您没有使用完全匹配。
10: const shouldBeOk: someOtherType = {
^ 无法分配对象文字,shouldBeOk因为属性keyOne在对象类型1 中缺失,但在对象文字2 中存在 。参考文献: 6: type someOtherType = someType & {|
^ 1 10: const shouldBeOk: someOtherType = {
^ 2
正确的做法是使用以下spread操作:
type someOtherType = {|
...someType,
keyThree: string
|}
Run Code Online (Sandbox Code Playgroud)