首页 > 解决方案 > 有没有办法通过链接变量名来访问打字稿中的子对象

问题描述

我试图替换的代码:

this.selectedArray1.indexOf(someIndexObject);

我试图用以下代码替换它:

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

当我进行上述替换时,虽然它给了我一个编译错误

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

在打字稿中可以做这样的事情吗?

标签: javascripttypescript

解决方案


默认情况下,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
    }
}

推荐阅读