dcs*_*san 8 methods dynamic-programming dispatch typescript
我有一个对象,我想动态调用它的方法。
进行类型检查会很好,但这可能是不可能的。但目前我什至无法编译它:
const key: string = 'someMethod'
const func = this[key]
func(msgIn)
Run Code Online (Sandbox Code Playgroud)
给我这个错误...
Element implicitly has an 'any' type
because expression of type 'any' can't be used
to index type 'TixBot'.
Run Code Online (Sandbox Code Playgroud)
我尝试了一些其他类型的选项但没有成功。
const key: any = cmd.func
const func: any = this[key]
Run Code Online (Sandbox Code Playgroud)
除了@ts-ignore我怎么能解决这个问题?我想知道我是否可以使用.call()或bind以某种方式解决它?
如果 Typescript 无法检查所使用的字符串是否是该类的有效成员,它就会出错。例如,这将起作用:
class MyClass {
methodA() {
console.log("A")
}
methodB() {
console.log("B")
}
runOne() {
const random = Math.random() > 0.5 ? "methodA" : "methodB" // random is typed as "methodA" | "methodB"
this[random](); //ok, since random is always a key of this
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,从常量中删除显式类型注释应该为您提供文字类型并允许您使用 const 来索引到this.
您还可以将字符串键入为keyof Class:
class MyClass {
methodA() {
console.log("A")
}
methodB() {
console.log("B")
}
runOne(member: Exclude<keyof MyClass, "runOne">) { // exclude this method
this[member](); //ok
}
}
Run Code Online (Sandbox Code Playgroud)
如果您已经有一个string使用断言 tokeyof MyClass也是一个选项,尽管这不是类型安全的(this[member as keyof MyClass]where let member: string)
| 归档时间: |
|
| 查看次数: |
4217 次 |
| 最近记录: |