【发布时间】: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