【发布时间】:2020-12-14 04:27:25
【问题描述】:
我正在尝试检查联合类型变量的值的类型。
/* @flow */
type A = {
a: number,
b: number
}
type B = {
c: string
}
const fun1: (A | B) => void = (x) => {
if (x.a) {
x.a
x.b // Doesn't work
}
if (x.b) {
x.b
x.a // Doesn't work
}
if (x.c) {
x.c
}
}
检查单个属性是唯一的方法吗?在上面的例子中,我们知道如果x.a,那么也是x.b。有没有办法检查A 类型或B 类型所以我可以写
const fun1: (A | B) => void = (x) => {
if (typeof x === 'A') { // Cannot compare the result of `typeof` to string literal `A` because it is not a valid `typeof` return value.
x.a // Works
x.b // Works
}
}
【问题讨论】:
标签: functional-programming flowtype