当我在另一个类 Wrapper
中使用 Test
类时,我希望能够将方法代理到通用中的 test
实例方式 this.test[method]()
.
在这种情况下,我只想代理fly
swim
和drive
(三者的签名相同)。
然而,问题出在 Test
类的其他方法中,这就是 TypeScript 提示的地方。
在第一个 //1. addEventListener
中,如果我尝试使用 keysof
那么 TypeScript 会因为方法签名而提示。
在第二个 //2. addEventListener
我试图通过 Pick
实用程序类型创建一个新类型 CustomMethods
,但后来我得到了错误 CustomMethod 不能用作索引类型
有没有办法在--strict
模式下编译这段代码?
class Test {
fly(location: string, listener: Function) {}
swim(location: string, listener: Function) {}
drive(location: string, listener: Function) {}
stopFlying(birds:number[]){}
stopDriving(racers:boolean[]){}
}
// pick some of the 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);
}
}
最佳答案
你需要keyof Pick<Test, "fly" | "swim"| "drive">
,不只是 Pick<Test, "fly" | "swim"| "drive">
.
关于 typescript 包装对象并仅代理它的一些方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57976606/