我在 TypeScript 中有这段代码:
type NameValue = { name: string; value: string };
type MixedStuff = NameValue | string;
function stripTwoChars(stuffs: MixedStuff[]): string {
let stuffZero = stuffs[0];
return (typeof stuffZero === "string" ?
stuffZero.slice(0, 2) :
stuffZero.name.slice(0, 2)); // This works fine
return (typeof stuffs[0] === "string" ?
stuffs[0].slice(0, 2) : // Here error: no slice on NameValue
stuffs[0].name.slice(0, 2)); // Here error: no name on string
}
因此,正如您在函数中看到的那样,首先我将第一个列表项保存在一个变量中,然后对其进行 typeof 检查,效果很好。
但如果我直接对第一个列表项执行 typeof,类型检查将不起作用。
这是一个错误还是为什么会这样?
最佳答案
是的,这是设计使然,数组访问表达式的类型保护被考虑但被拒绝了。参见讨论 here
Declined due to performance reasons. Since it should almost always be possible to write
const j = list[i]
instead, this shouldn't be too burdensome.
关于 typescript :typeof checkin 列表项不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50968983/