以下代码会导致错误:
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/