javascript - FlowJS - 给出类型错误,因为它无法识别 `typeof` 语句的结果

标签 javascript flowtype

以下代码会导致错误:

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)的解决方案。

最佳答案

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];
    

关于javascript - FlowJS - 给出类型错误,因为它无法识别 `typeof` 语句的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53199219/

相关文章:

javascript - 页面重新加载时变量的值发生变化

javascript - JQuery DatePicker 忽略 DateFormat

javascript - 流类型检查 : undefined is not a function even if there is a conditional

javascript - Reacts `propTypes` 和 `defaultProps` 应该和 Flowtype 一起使用,还是 Flowtype 够全面?

c# - 如何使用 GeckoFX 作为 XULRunner 的包装器在 javascript 中调用 C# 方法

javascript - 如何将事件监听器附加到 JS 中的对象

javascript - 处理回调选项在 jQuery 文件上传中不起作用

reactjs - 输入 react - Prop 为 `type` 或 `interface`

javascript - 使用Flow时如何向Error对象添加调试信息?

javascript - Flow 和 Immutable.js 映射