typescript - 在打字稿中按名称获取方法
问题描述
我知道如何在 javascript 中获取对象的方法(使用括号表示法)但不明白如何在 Typescript 中实现相同的目标?
当试图做得到this[methodName]
错误[ts] Element implicitly has an 'any' type because type 'MyWebSocket' has no index signature. [7017]
解决方案
您必须使用类型断言来告诉编译器该methodName
值是受限制的,因此它只能是为this
.
例如
this[methodName as 'method1' | 'method2']
或者,如果您有一些名为的接口,例如在其中声明Methods
了您要调用的所有方法this
this[methodName as keyof Methods]
as any
另一种解决方案是使用类型断言选择退出类型检查:
(this as any)[methodName]
推荐阅读
- r - rbind 数据框后出现两个同名列表
- sql - SQL 根据一组值过滤重复项
- arrays - 在数组的“每个”方法上返回 nil
- tsql - 根据连续匹配记录标记 SQL 记录中的组
- google-maps - 使用 Dart 出行时如何计算等待时间?
- python - 网络抓取冠状病毒互动图
- kubernetes - Prometheus Exporter 无法访问,有什么方法可以调查?
- mysql - 创建数据库时,我们是否必须留出一些空间以防万一?
- google-chrome-extension - Chrome 扩展程序失去了 activeTab 权限
- java - 如何在不重新初始化的情况下更改令牌标签?