I am looking to enhance an object by adding a method that specifically accepts the name of another method within the object. How can I achieve this in a way that dynamically narrows down the accepted names of methods, without hardcoding them?
Let's take the command
method in the User
class as an example. We want the command
method to only accept the name of another method within the User
class. How can we use keyof this
to narrow down the acceptable types to only method names, excluding properties?
class User {
nameFirst: string;
nameLast: string;
command(commandName: keyof this) {
this[commandName].call(this);
}
sink() {}
swim() {}
}
const alice = new User();
alice.command(`swim`); // Currently accepts `nameFirst` | `nameLast` | `command` | `sink` | `swim`, but we want it to accept only `sink` and `swim`