TS2538类型“未定义”不能用作索引类型。当支票分配给变量时

jep*_*pek 5 javascript typescript

我收到TS错误:

TypeScript错误:类型'undefined'不能用作索引类型。TS2538

对于此简单功能(根据提供的索引从数组中获取对象):

const myArr: Array<object> = [{name: 'John'}, {name: 'Tom'}]

function getData(index?: number) {
    const isIndex : boolean = typeof index !== 'undefined';

    return isIndex ? myArr[index] : {};
}
Run Code Online (Sandbox Code Playgroud)

对我来说,更神秘的是,当我将其更改为:

function getData(index?: number) {
    return typeof index !== 'undefined' ? myArr[index] : {};
}
Run Code Online (Sandbox Code Playgroud)

一切都像魅力一样-为什么?

Raj*_*han 3

由于代码流中的间接性,Typescript 将不会按预期执行代码分析。这时,用户定义的类型防护就可以发挥作用了。

function isUndefined(index: any): index is boolean {
    return typeof index === "undefined";
}

function getData(index?: number) {
    return isUndefined(index) ? {} : myArr[index];
}
Run Code Online (Sandbox Code Playgroud)

因为索引在getData方法中是可选的,所以它可能是undefined,你的第二种技术有效。