有没有办法通过链接变量名来访问打字稿中的子对象

时间:2018-07-26 13:32:18

标签: javascript typescript

我要替换的代码:

this.selectedArray1.indexOf(someIndexObject);

我要替换为的代码:

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

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

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

正在打字稿中做类似的事情吗?

1 个答案:

答案 0 :(得分: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
    }
}
相关问题