我有一个函数,它接受两个不相交的精确类型的并集,并构造一个新对象。 react documentation表示使用不相交的精确类型,我应该能够通过检查属性的存在来推断类型。但是,这似乎不起作用-我的else分支指示其中一种类型的属性丢失。
type Sid = {|
val: string,
id: number
|};
type Entity ={
idOrName: Sid | string,
optionalDescription: ?string
}
const createEntity = (idOrNameAndDescription: Sid | {| name: string, description: string |}): Entity => {
if (idOrNameAndDescription.val) {
return {
idOrName: idOrNameAndDescription,
optionalDescription: null
}
} else {
return {
// These next to lines fail, saying:
// "Flow: Cannot get `idOrNameAndDescription.name` because
// property `name` is missing in `Sid`
idOrName: idOrNameAndDescription.name,
optionalDescription: idOrNameAndDescription.description
}
}
}
请参见else / return语句中的注释。给出的错误是:
Cannot get idOrNameAndDescription.name because property name is missing in Sid [1].
[1] 60│ const createEntity = (idOrNameAndDescription: Sid | {| name: string, description: string |}): Entity => {
:
65│ }
66│ } else {
67│ return {
68│ idOrName: idOrNameAndDescription.name,
69│ optionalDescription: idOrNameAndDescription.description
70│ }
71│ }
Cannot get idOrNameAndDescription.description because property description is missing in Sid [1].
[1] 60│ const createEntity = (idOrNameAndDescription: Sid | {| name: string, description: string |}): Entity => {
:
66│ } else {
67│ return {
68│ idOrName: idOrNameAndDescription.name,
69│ optionalDescription: idOrNameAndDescription.description
70│ }
71│ }
72│ }
但是,由于未定义.val
,因此流程应该知道它属于联合的另一半,并且定义了name
和description
。
我还尝试过使用if (idOrNameAndDescription.val != null)
,这会使if语句的两个分支以及if (typeof idOrNameAndDescription.val === 'string')
都无效,从而导致更加难看的错误。
这是流虫还是我错过了什么?