Javascript FlowJS-给出类型错误,因为它无法识别'typeof'语句的结果
以下代码导致错误:Javascript FlowJS-给出类型错误,因为它无法识别'typeof'语句的结果,javascript,flowtype,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.
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
变量,并希望代码保持干爽和简单(易于阅读)。因此,请不要使用“聪明”(黑客)的解决方案。Flow的改进通常基于使用时的直接检查,因此它只会将您的isString
变量视为布尔值,没有特殊意义
这就给您留下了几个单独的选项:
- 调整代码的控制流,使其有两个清晰的分支,假设对
isString
有更多的检查,则始终可以创建一个清晰的分支来处理这两种情况
- 内联下一步的
typeof==“string”
检查
const toName = typeof next === 'string' ? next : Object.keys(next)[0];
- 使用a集中化
isString
逻辑
function isString(arg: mixed): boolean %checks {
return typeof arg === "string";
}
const toName = isString(next) ? next : Object.keys(next)[0];
可以使用嵌套在自己的块中运行所有字符串代码吗,例如,if(typeof next=='string'){/*所有字符串内容*/}或者{/*所有对象内容*/}
?也许,这是一个切实可行的解决方案。它会产生更多的代码(三元数的更长形式),但至少可以工作。你介意发布一个答案吗,因为这是我找到的唯一可行的解决方案。谢谢实用方法(选项3)是赢家。我还不知道flowtype中的谓词。谢谢