【问题标题】:Comparing enum values in Flow比较 Flow 中的枚举值
【发布时间】:2018-01-14 18:38:02
【问题描述】:

我正在使用flow 在我的代码中注释类型。

type Bar = 'One' | 'Two';
function foo(b: Bar) : boolean {
  return b === 'Three';
}

有什么方法可以教flow 报告与非匹配类型(在我的情况下为string)比较时的警告或错误?

here is the example for test

edit: 所以似乎不可能使用枚举。但是,由于这实际上是我遇到的一个错误,所以我想表达一下,以便 flow 可以帮助我标记这种情况。

对此有什么想法吗?

【问题讨论】:

标签: javascript types flowtype


【解决方案1】:

这是我能想到的另一种方式:

type Bar = 'One' | 'Two';

function eq(a: Bar, b: Bar): boolean {
  return a === b;
}
function foo(b: Bar) : boolean {
  // compare b to 'Three'
  return eq(b, 'Three');
}

会导致

return eq(b, 'Three');
                  ^ string. This type is incompatible with the expected param type of 
function eq(a: Bar, b: Bar): boolean {
                       ^ string enum

to be found here

【讨论】:

    【解决方案2】:

    您可以使用 (value: Type) 格式。在你的情况下,这将是:

    类型栏 = '一个' | '二'; 函数 foo(b: Bar) : boolean { return b === ("三": Bar); }

    这将显示错误。

    Updated example.

    【讨论】:

    • 虽然我曾希望 === 本身可以以某种方式成为类型安全的,但这个解决方案对我有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 2012-05-04
    相关资源
    最近更新 更多