我要替换的代码:
this.selectedArray1.indexOf(someIndexObject);
我要替换为的代码:
var someVariable = "selectedArray1"
this[someVariable].indexOf(someIndexObject);
当我进行上述替换时,尽管它给了我一个编译错误
TS2538: Type 'String' cannot be used as an index type
正在打字稿中做类似的事情吗?
答案 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
}
}