所以我有以下代码:
type Something =
| { t: 'A', src: string }
| { t: 'B', src: string }
| { t: 'C', src: number };
const f = (o: Something): string =>
o.t === 1
? o.src
: 'a-string';
当 o.t
为 1 时,我希望在返回 o.src
时看到错误,因为我从未定义过 t
可以是数字。因此,如果 t
是数字,则流程不知道 o.src
的类型是什么。但它的工作没有任何错误。我在这里缺少什么?
这是flow/try .
根据记录,TypeScript version正确抛出错误。尽管错误消息没有那么有用。
为了澄清一点,如果我使用 o.t === 'F'
来代替,那么 flow 会很高兴地抛出以下错误:
9: o.t === 'F' ^ all branches are incompatible: Either object with property
t
that matches string literalF
1 is incompatible with string literalA
2. Or object with propertyt
that matches string literalF
1 is incompatible with string literalB
[3]. Or object with propertyt
that matches string literalF
1 is incompatible with string literalC
[4]. References: 9: o.t === 'F' ^ 1 4: | { t: 'A', src: string } ^ 2 5: | { t: 'B', src: string } ^ [3] 6: | { t: 'C', src: number }; ^ [4]
我不知道为什么,但这只是不一致的行为,如果我使用类型中未定义的值,我预计会看到一些错误。你知道,就像一段无法访问的代码。
最佳答案
这取决于===
的语义。根据ECMA specification ,运算符的定义如下(至少是重要的一点):
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
- If Type(x) is different from Type(y), return false.
- ...other steps...
您实际上不必查看第 1 步。您的表达式 o.t === 1
可以视为:
typeof o.t == typeof 1 && (...other steps...)
只有该表达式的第一部分会被计算,因为它可能被证明是错误的。 Flow 知道您永远不会真正将数字与字符串进行比较。
正如其他人已经回答的那样,您应该将 ==
与 Flow 一起使用。
关于javascript - 流联合类型不会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50049214/