javascript - 流联合类型不会出错

标签 javascript typescript flowtype union-types

所以我有以下代码:

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 literal F 1 is incompatible with string literal A 2. Or object with property t that matches string literal F 1 is incompatible with string literal B [3]. Or object with property t that matches string literal F 1 is incompatible with string literal C [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:

  1. If Type(x) is different from Type(y), return false.
  2. ...other steps...

您实际上不必查看第 1 步。您的表达式 o.t === 1 可以视为:

typeof o.t == typeof 1 && (...other steps...)

只有该表达式的第一部分会被计算,因为它可能被证明是错误的。 Flow 知道您永远不会真正将数字与字符串进行比较。

正如其他人已经回答的那样,您应该将 == 与 Flow 一起使用。

关于javascript - 流联合类型不会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50049214/

相关文章:

javascript - 访问嵌套流类型

javascript - 为什么 Flow 拒绝由并集的交集组成的元组?

flowtype - "exponentially large number of cases"最新流中的错误,具有常见的传播模式

javascript - 在tinymce上自动点击

javascript - 为什么 chrome 控制台不返回 undefined 在这里?

javascript - 如何在 react.js 中过滤多个数组上的对象列表?

angular - 如何动态添加mat-expansion panel?

javascript - 在 JavaScript 中,只有变量名的语句会执行某些操作吗?

javascript - 具有指令和隔离范围的 Controller

javascript - 在 ExtJS 组合框中调整下拉列表