如何在打字稿中动态调用实例方法?
how to dynamically call instance methods in typescript?
我有一个对象,我想对其动态调用一个方法。
进行类型检查会很好,但这可能是不可能的。
但是我现在根本无法编译它:
const key: string = 'someMethod'
const func = this[key]
func(msgIn)
给我这个错误...
Element implicitly has an 'any' type
because expression of type 'any' can't be used
to index type 'TixBot'.
我尝试了一些其他类型的选项但没有成功。
const key: any = cmd.func
const func: any = this[key]
除了 @ts-ignore
我该如何解决这个问题?
我想知道我是否可以使用 .call()
或 bind
以某种方式解决它?
如果无法检查所使用的字符串是否为 class 的有效成员,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
}
}
在上面的示例中,从常量中删除显式类型注释应该会为您提供文字类型,并允许您使用常量索引到 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
}
}
如果你已经有一个 string
使用断言到 keyof MyClass
也是一个选项,尽管这不是类型安全的(this[member as keyof MyClass]
其中 let member: string
)
我有一个对象,我想对其动态调用一个方法。
进行类型检查会很好,但这可能是不可能的。 但是我现在根本无法编译它:
const key: string = 'someMethod'
const func = this[key]
func(msgIn)
给我这个错误...
Element implicitly has an 'any' type
because expression of type 'any' can't be used
to index type 'TixBot'.
我尝试了一些其他类型的选项但没有成功。
const key: any = cmd.func
const func: any = this[key]
除了 @ts-ignore
我该如何解决这个问题?
我想知道我是否可以使用 .call()
或 bind
以某种方式解决它?
如果无法检查所使用的字符串是否为 class 的有效成员,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
}
}
在上面的示例中,从常量中删除显式类型注释应该会为您提供文字类型,并允许您使用常量索引到 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
}
}
如果你已经有一个 string
使用断言到 keyof MyClass
也是一个选项,尽管这不是类型安全的(this[member as keyof MyClass]
其中 let member: string
)