typescript :typeof checkin 列表项不起作用

标签 typescript

我在 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/

相关文章:

angular - 类型 'Subscription' 缺少以下属性

javascript - 获取错误 TypeError : Promise. 任何不是函数

javascript - 如何在 JavaScript 中使用循环将十六进制转换为十进制

typescript - 如何为对象数组定义接口(interface)?

angular - 如何动态设置组件宿主样式Angular 8

typescript - typings 可以从 package.json 自动安装 d.ts 吗?

javascript - Angular Material 垫步进器 : How to use the same formgroup for multiple steps?

javascript - 如何在 Vue 类组件中定义过滤器?

javascript - 在 NodeJS 和 Typescript 中从 csv 转换为 json 后如何打印 json 数组中的单个键和值

javascript - 如何将文件连同数据从 Angular 上传到 .NET Core