es6 class 函数中的 this[functionName] 导致 "Element implicitly has an 'any' type because expression of type string can't be used to index"
this[functionName] in an es6 class function cause "Element implicitly has an 'any' type because expression of type string can't be used to index"
我正在尝试使用 es6 classes 创建类似服务的命令,如下所示:
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'.
在这种情况下如何将“名称”参数定义为 class Person 成员类型?
定义名称类型如下
execute(name: "talk" | "walk" | "run") {
this[name]()
}
鉴于键可以是除 execute
本身之外的任何 class 键,您可以按如下方式定义参数类型:
execute(name: Exclude<keyof Person, 'execute'>){
this[name]();
}
您可以在此 TypeScript playground 上看到它的实际效果。
我正在尝试使用 es6 classes 创建类似服务的命令,如下所示:
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'.
在这种情况下如何将“名称”参数定义为 class Person 成员类型?
定义名称类型如下
execute(name: "talk" | "walk" | "run") {
this[name]()
}
鉴于键可以是除 execute
本身之外的任何 class 键,您可以按如下方式定义参数类型:
execute(name: Exclude<keyof Person, 'execute'>){
this[name]();
}
您可以在此 TypeScript playground 上看到它的实际效果。