typescript - es6 类函数中的 this[functionName] 导致“元素隐式具有 'any' 类型,因为字符串类型的表达式不能用于索引”
问题描述
我正在尝试使用 es6 类创建类似服务的命令,如下所示:
class Person {
run(){
console.log("running");
}
walk(){
console.log("walking");
}
talk(){
console.log("talking");
}
execute(name: string){
this[name]()
}
}
const me = new Person();
me.execute('run');
me.execute('walk');
me.execute('talk');
这是完全有效的,但打字稿this[name]
部分是吠叫:
TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Person'.
在这种情况下,如何将“name”参数定义为 Person 的类成员类型?
解决方案
鉴于键可以是除execute
自身之外的任何类键,您可以按如下方式定义参数类型:
execute(name: Exclude<keyof Person, 'execute'>){
this[name]();
}
你可以在这个TypeScript playground上看到它的实际效果。
推荐阅读
- javascript - 单击按钮推送一个数组并返回另一个数组
- sql - SQL 异常:无效的对象名称,ASP.NET MVC
- java - netbeans中的javafx测试运行失败
- java - 容器级别的 Azure 存储指标
- java - Flink 读取 S3 文件导致 Jackson 依赖问题
- r - 在一个方向上创建误差线,一种特殊情况
- reactjs - this.props 反应训练问题 - CodeAcademy
- java - Java String 对象相等和引用
- javascript - 我们可以从 javascript 文件发送 ajax 吗?
- spring-boot - spring-ws - Oracle Weblogic 12c