首页 > 解决方案 > 在打字稿中按名称获取方法

问题描述

我知道如何在 javascript 中获取对象的方法(使用括号表示法)但不明白如何在 Typescript 中实现相同的目标?

当试图做得到this[methodName]错误[ts] Element implicitly has an 'any' type because type 'MyWebSocket' has no index signature. [7017]

标签: typescripttypescript-typings

解决方案


您必须使用类型断言来告诉编译器该methodName值是受限制的,因此它只能是为this.

例如

this[methodName as 'method1' | 'method2']

或者,如果您有一些名为的接口,例如在其中声明Methods了您要调用的所有方法this

this[methodName as keyof Methods]

as any另一种解决方案是使用类型断言选择退出类型检查:

(this as any)[methodName]

推荐阅读