网站搜索

javascript - 在 TypeScript 中有办法通过链式变量名访问子对象吗


我正在尝试替换的代码:

this.selectedArray1.indexOf(someIndexObject);

我打算用来替换它的代码:

var someVariable = "selectedArray1"
this[someVariable].indexOf(someIndexObject);

但是当我进行上述替换时,它会给我编译错误

TS2538: Type 'String' cannot be used as an index type

在 TypeScript 中做类似的事情可能吗?

答案#1

TypeScript 默认会阻止你这样做,除非它能证明该字符串是该类型的键,或者该类型有索引签名

用已知是关键的东西:

class Foo {
    selectedArray1 = [];
    method(){
        this['selectedArray1'] //ok the result is of the same type as the field
        const s = 'selectedArray1'; // ok
        this[s] // ok, the result is of the same type as the field
        var someVariable = "selectedArray" + 1 // not provable to be a key
        this[someVariable]  // error
        this[someVariable as keyof this] // but ok with an assertion, but is a union of all field types of this
    }
}

或者使用索引签名:

class Foo {
    [s: string] : any
    selectedArray1 = [];
    method(){
        var someVariable = "selectedArray" + 1 // not provable to be a key
        this[someVariable]  // ok, anything goes is of type any
    }
}