We have created a foundational class that will be extended numerous times. Our goal is to implement an `exec` method on this base class, which will take the name and arguments of a method from a derived class and execute it.
However, we are encountering an issue with the typing of the arguments in the method of the derived class. The code snippet below demonstrates the error:
class BaseClass {
exec<
Self extends Record<MethodKey, (...args: any) => void>,
MethodKey extends keyof Self,
Method extends Self[MethodKey],
>(
this: Self,
methodKey: MethodKey,
...args: Parameters<Method>
) {
this[methodKey](...args);
}
}
class MyClass extends BaseClass {
constructor() {
super();
this.exec(`sayMessage`, `Hello`); // Error: Argument of type '["Hello"]' is not assignable to parameter of type 'Parameters<this["sayMessage"]>'.
}
sayMessage(message: string) {
console.log(message);
}
}
Why does this setup fail, and how can we correctly define the typing for the `exec` method to accept arguments from another method?