javascript - 有没有办法通过链接变量名来访问打字稿中的子对象
问题描述
我试图替换的代码:
this.selectedArray1.indexOf(someIndexObject);
我试图用以下代码替换它:
var someVariable = "selectedArray1"
this[someVariable].indexOf(someIndexObject);
当我进行上述替换时,虽然它给了我一个编译错误
TS2538: Type 'String' cannot be used as an index type
在打字稿中可以做这样的事情吗?
解决方案
默认情况下,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
}
}
推荐阅读
- python - 使用字符串处理选择某些数据框列
- jenkins - Jenkins groovy.lang.MissingMethodException:没有方法签名:catchError()
- python - 在终端打印时,会出现额外的替换字符“�”(U+FFFD)
- java - 从另一个类扩展的类可以使用具有不同返回类型的相同方法吗?
- node.js - npm 中的“生产”标志有什么用?
- c# - 从 https 下载文件适用于 Chrome,但不适用于 C#
- jenkins - filter-by-name-wildcard 在带有 git 的 Jenkins Job-Builder 中不起作用,因为它在用于多分支管道的 Jenkins Web 界面中
- javascript - React 中的错误:渲染的钩子比上一次渲染时更多
- python - 在决策树中查找到决策边界的距离
- c++ - 让细节命名空间代码看不见 - 优雅