TypeScript中如何通过字符串名调用当前类的实例方法
报错根源
ts(7053) 是TypeScript静态类型系统的基础校验规则:类的实例默认不支持任意字符串值的索引操作,编译器无法校验传入的字符串是否真的对应类上存在的属性,也无法校验对应属性的类型是否符合调用要求,从编译阶段避免运行时出现“读取不存在的属性、调用非函数值”的低级错误。
可行的解决方式
- 方法1:收窄方法名字符串的类型范围
不要将存储方法名的变量声明为宽泛的string类型,改用keyof 类名的类型限定,告诉TS这个字符串一定是类上的合法键,即可正常完成索引和调用,且保留完整的类型校验能力。
对应示例代码:class AnObject { aFunction() { // 类型收窄:限定functionName必须是AnObject上的合法键 let functionName: keyof AnObject = "anotherFunction" let param1: string = "abc" let param2: number = 123 // TS可正常识别属性类型,支持直接调用 const targetMethod = this[functionName] if (typeof targetMethod === "function") { targetMethod(param1, param2) } } anotherFunction = (paramA: string, paramB: number) => { console.log(`called anotherFunction---${paramA} and ${paramB}`) } } - 方法2:动态字符串场景下做精准类型断言
如果方法名是外部传入的动态值,无法提前在编译期确定合法范围,不要为了消错直接写as any,可以通过两层校验既绕过TS的索引限制,又保留运行时安全和类型检查:- 对字符串值做断言,告知TS这是类的合法键
as keyof AnObject - 校验取出的属性确实是函数类型,再对函数的入参/返回值做精准断言
对应示例代码:
class AnObject { private runDynamicCall(methodName: string, p1: string, p2: number) { const targetKey = methodName as keyof AnObject const targetProp = this[targetKey] // 运行时校验属性确实是函数 if (typeof targetProp !== "function") return // 对函数签名做精准断言,保证调用参数类型正确 (targetProp as (arg1: string, arg2: number) => void)(p1, p2) } aFunction() { let functionName: string = "anotherFunction" this.runDynamicCall(functionName, "abc", 123) } anotherFunction = (paramA: string, paramB: number) => { console.log(`called anotherFunction---${paramA} and ${paramB}`) } } - 对字符串值做断言,告知TS这是类的合法键
避坑提示
- 不要直接给类添加
[index: string]: any的通用字符串索引签名来消错,这种写法会完全废掉类的类型校验能力,后续哪怕写错属性名、传错参数,TS都不会给出报错提示,属于因小失大的做法。 - 原示例中
Function.apply(this[prop], ["ABC", "123"] )的写法是无效的:它本质是调用全局Function构造器,将其内部this指向目标方法,不会触发目标方法的执行逻辑,和我们想要的"绑定this并调用目标方法"完全不是一回事。如果需要手动绑定上下文调用目标方法,应该用目标函数自身的apply/call方法实现,正确写法示例:(this[prop] as typeof this["anotherFunction"]).apply(this, ["ABC", 123])
内容的提问来源于stack exchange,提问作者user3525213
相关产品推荐
相关产品推荐

