When utilizing the Test
class within another class named Wrapper
, I aim to be able to delegate the methods to the test
instance in a universal manner, like so: this.test[method]()
.
In this scenario, my intention is only to delegate the fly
, swim
, and drive
methods (all with the same signature). However, the issue lies in other methods of the Test
class, which is where TypeScript raises concerns.
Within the first // 1. addEventListener
, if I attempt to use keysof
, TypeScript gives me an error due to the method signatures.
In the second // 2. addEventListener
, I tried creating a new type called CustomMethods
using the Pick
utility type, but encountered the error message "
CustomMethod cannot be used as an index type
".
Is there a way to compile this code in --strict
mode?
class Test {
fly(location: string, listener: Function) {}
swim(location: string, listener: Function) {}
drive(location: string, listener: Function) {}
stopFlying(birds:number[]){}
stopDriving(racers:boolean[]){}
}
// picking specific methods from the Test type
type CustomMethods = Pick<Test, "fly" | "swim"| "drive">;
class Wrapper {
public name: string;
public test: Test;
constructor(t:Test) {
this.name = "event";
this.test = t
}
// 1.
addListener(method: keyof Test, listener: Function) {
this.test[method](this.name, listener);
}
// 2.
addListener(method: CustomMethods, listener: Function) {
this.test[method](this.name, listener);
}
}
typescript playground demo