我正在尝试在TypeScript中使用ES6 Mixin。我所拥有的内容如下所示,它与BaseClass
完美配合。
class BaseClass {
public foo() {}
};
interface IMyMixin {
foo2();
}
let MyMixin = (superclass: typeof BaseClass) => class extends BaseClass implements IMyMixin {
public foo2() {}
}
class MyBaseClass extends MyMixin(BaseClass) {
}
但是,我无法对来自MyMixin
的派生类应用BaseClass
;与此同时,我也无法制作mixin泛型。
有没有办法让它适用于BaseClass
和DerivedClass
?
class DerivedClass extends BaseClass {
public bar() {}
}
class MyDerivedClass extends MyMixin(DerivedClass) {
public something() {
// Compile Error: Property 'bar' does not exist on type 'MyDerivedClass'
this.bar();
}
}
// Compile Error: 'T' only refers to a type, but is being used as a value here.
let MyMixin = <T extends BaseClass>(superclass: typeof T) => class extends T implements IMyMixin {
public foo2() {}
}
答案 0 :(得分:1)
我找到了来自TypeScript/PR#13743的解决方案,并通过@Maximus的评论对其进行了优化。
这段代码有效。原因是,在MyMixin
中,T
应该是Class
(即构造函数),而不是类型。
type Constructor<T> = new (...args: any[]) => T;
class BaseClass {
public foo() { }
};
interface IMyMixin {
foo2();
}
// `implements IMyMixin` is optional.
let MyMixin = <T extends Constructor<BaseClass>>(superclass: T) => class extends superclass implements IMyMixin {
public foo2() { }
}
class DerivedClass extends BaseClass {
public bar() {}
}
class MyDerivedClass extends MyMixin(DerivedClass) {
public something() {
this.bar();
this.foo();
this.foo2();
}
}