我有这个扩展子类型的联合示例:
type TypeA = {|
type: "a",
value: number,
|};
type TypeB = {|
type: "b",
value: Array<number>,
|};
type SuperType =
| TypeA & {|
color: string,
|}
| TypeB;
function test(val: SuperType): void {
if (val.type === "b") {
// Flow should probably know that val.value is an array here
console.log(val.value.length);
}
}
但是,最后,当我尝试利用Disjoint Unions with exact types时,它失败了:
20: console.log(val.value.length);
^ Cannot get `val.value.length` because property `length` is missing in `Number` [1].
References:
3: value: number,
^ [1]
我不知道是Flowtype不支持这个,还是我做错了什么。这发生在流0.66上。请注意,如果我删除了{| color: string |}
位,这将起作用。
发布于 2018-03-01 20:41:32
在SuperType
中,使用展开运算符...
而不是交集运算符&
type TypeA = {|
type: "a",
value: number,
|};
type TypeB = {|
type: "b",
value: Array<number>,
|};
type SuperType =
| {|
...TypeA,
color: string,
|}
| TypeB;
function test(val: SuperType): void {
if (val.type === "b") {
// Flow should probably know that val.value is an array here
console.log(val.value.length);
}
}
https://stackoverflow.com/questions/49049633
复制相似问题