【发布时间】:2021-07-09 17:23:00
【问题描述】:
给定以下代码:
type CustomTypeA = {
x: number,
y: number,
}
type CustomTypeB = CustomTypeA & {
z: number,
}
type CustomType = CustomTypeA | CustomTypeB
export const myFunction = (a: CustomType | number): number | void => {
if (typeof a === 'number') {
return a; // THIS WORKS WELL, it's considered number after the check, which is correct
} else if (typeof a === CustomType) {
const newX = a.x // ERR: Flow: Cannot get `a.x` because property `x` is missing in `Number`
const newZ = a.z // SAME ERR, Flow: Cannot get `a.z` because property `z` is missing in `Number`.
}
}
此外,typeof a === CustomType 检查也会突出显示为错误:
Flow: Cannot reference type `CustomType` from a value position.
但typeof a === 'number' 不会发生这种情况。
这就像对我创建的自定义对象类型的检查无效/无法识别。
有人可以解释为什么以及可能如何逃避这种情况吗? 谢谢。
【问题讨论】:
标签: object types reference flowtype