以下代码导致错误:
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
变量,并希望保持我的代码 DRY 和 SIMPLE(易于阅读)。所以请不要“聪明”(hacky)解决方案。
Flow 的改进通常基于使用时的直接检查,因此它只会将您的isString
变量视为boolean
没有特殊含义的变量。
这给您留下了几个单独的选项:
isString
,您总是可以创建一个明确的分支来处理这两种情况。内联typeof next === 'string'
支票。
const toName = typeof next === 'string' ? next : Object.keys(next)[0];
使用谓词函数来集中isString
逻辑
function isString(arg: mixed): boolean %checks {
return typeof arg === "string";
}
const toName = isString(next) ? next : Object.keys(next)[0];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句