【问题标题】:FlowJS - gives a type error because it cannot recognize the result of a `typeof` statementFlowJS - 给出类型错误,因为它无法识别 `typeof` 语句的结果
【发布时间】:2018-11-08 15:41:34
【问题描述】:

以下代码导致错误:

type NextItem = string | { [string]: string };

const next: NextItem = 'foo';
const isString = typeof next === 'string';
const toName = isString ? next : Object.keys(next)[0];
                                 ^ string [1] is not an object.

但是去掉 isString 变量可以解决这个问题:

type NextItem = string | { [string]: string };

const next: NextItem = 'foo';
const toName = typeof next === 'string' ? next : Object.keys(next)[0];

我理解为什么,但我希望有人可以提供更好的解决方案。我需要重用isString 变量,并希望保持我的代码既干燥又简单(易于阅读)。所以请不要使用“聪明”(hacky)的解决方案。

【问题讨论】:

  • 你可以使用嵌套来运行它自己的块中的所有字符串代码,例如if (typeof next === 'string') { /* all the string stuff */ } else { /* all the object stuff */ }?
  • 也许,这是一个切实可行的解决方案。它会产生更多代码(更长的三元形式),但至少它可以工作。您介意发布答案吗,因为这是我找到的唯一可行的解​​决方案。谢谢!

标签: javascript flowtype


【解决方案1】:

Flow 的改进通常基于使用时的直接检查,因此它只会将您的isString 变量视为boolean,没有特殊含义。

这给您留下了几个单独的选择:

  • 调整代码的控制流,以便有两个明确的分支,假设对isString 有更多检查,您始终可以创建一个明确的分支来处理这两种情况。
  • 内联typeof next === 'string' 检查。

    const toName = typeof next === 'string' ? next : Object.keys(next)[0];
    
  • 使用predicate function 集中isString 逻辑

    function isString(arg: mixed): boolean %checks {
       return typeof arg === "string"; 
    }
    
    const toName = isString(next) ? next : Object.keys(next)[0];
    

【讨论】:

  • 实用方法(选项 3)是赢家。我还不知道流类型中的谓词。谢谢!
猜你喜欢
  • 2021-08-12
  • 2020-08-28
  • 2022-01-21
  • 2019-10-11
  • 1970-01-01
  • 1970-01-01
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多