我有以下类型
type segment =
| { created_in: {account_id : string}}
| { updated_in: {account_id: string}};
具有以下解剖联合的功能:
const operate = (segment: segment): string => {
if (segment.created_in) {
return segment.created_in.account_id
} else if (segment.updated_in) {
return segment.updated_in.account_id;
} else {
return ""
}
}
流程在segment.created_in.account_id
上显示错误:
10: return segment.created_in.account_id
^ Cannot get `segment.created_in.account_id` because property `account_id` is missing in property `created_in` of unknown type [1].
References:
9: if (segment.created_in) {
^ [1]
为什么if (segment.created_in)
无法确定该分支位于{created_in: { account_id: string}
分支中?
答案 0 :(得分:1)
您可以通过对segment
的分支使用精确的对象类型来解决此问题,如下所示:
type segment =
| {| created_in: { account_id: string, foo: number } |}
| {| updated_in: { account_id: string } |};
确切的对象语法{| ... |}
告诉Flow,给定类型的对象可能没有列出的属性。默认情况下,对象类型是“开放的”:给定类型的对象必须具有类型定义中的属性,但可以具有其他属性。
使用默认的不精确类型,Flow不能根据您的检查来缩小类型的范围,因为它不确定是否知道具有属性created_in
的对象也没有名为updated_in
的属性。而且,如果确实具有这样的属性,则Flow不知道类型是什么,因为该属性未在类型声明中给出。因此,您看到的错误中提到了unknown type
。