Home > database >  this[functionName] in an es6 class function cause "Element implicitly has an 'any' ty
this[functionName] in an es6 class function cause "Element implicitly has an 'any' ty

Time:10-22

I'm trying to create a command like service using es6 classes like so:

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 is completely valid but typescript is barking on this[name] part:

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Person'.

How do I define the "name" parameter in this case to be a class member type of Person?

CodePudding user response:

Given the key could be any of the class keys except execute itself, you could define the parameter type as follows:

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

You can see it in action on this TypeScript playground.

CodePudding user response:

Define the name type as follows

execute(name: "talk" | "walk" | "run") {
    this[name]()
}
  • Related