首页 > 解决方案 > 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 的类成员类型?

标签: typescriptes6-class

解决方案


鉴于键可以是除execute自身之外的任何类键,您可以按如下方式定义参数类型:

execute(name: Exclude<keyof Person, 'execute'>){
   this[name]();
}

你可以在这个TypeScript playground上看到它的实际效果。


推荐阅读