typescript - 混入类的类型是什么
我无法弄清楚如何在不使用某种hack(如下所示)情况下获取TypeScript mixin类的类型
type Constructor<T = {}> = new(...args: any[]) => T;
function MyMixin<T extends Constructor>(BaseClass: T) {
return class extends BaseClass {doY() {}}
}
// Option A: Ugly/wasteful
const MixedA = MyMixin(class {doX() {}});
const dummy = new MixedA();
type MixedA = typeof dummy;
class OtherA {
field: MixedA = new MixedA();
a() {this.field.doX(); this.field.doY();}
}
// Option B: Verbose
class Cls {doX() {}}
interface MixinInterface {doY(): void}
const MixedB = MyMixin(Cls);
type MixedB = Cls & MixinInterface;
class OtherB {
field: MixedB = new MixedB();
a() {this.field.doX(); this.field.doY();}
}
我真的很难过 TypeScript 不支持真正的 mixins/traits,但有没有其他方法可以声明 field 的类型,而不必使用实例的 typeof 或重新在接口中声明签名(我尝试过 typeof(new MixedBaseA()),但 typeof 不接受任意表达式)?
答案#1
可能不是你想要的,但这里有一个更不浪费的替代方案。根据定义:
type Constructor<T = {}> = new(...args: any[]) => T;
function MyMixin<T extends Constructor>(BaseClass: T) {
return class extends BaseClass {
doY() { }
}
}
const MixedA = MyMixin(class { doX() {} });
你可以使用以下方式获取类型:
function getReturnType<R>(fn: (new(...args: any[]) => R)): R {
return {} as R;
}
const dummy = getReturnType(MixedA);
type MixedAType = typeof dummy;
const mixedA : MixedAType = new MixedA();
mixedA.doX();
mixedA.doY();
操场
获取任何表达式类型的提议仍在讨论中:https://github.com/Microsoft/TypeScript/issues/6606。这将消除虚拟变量和函数。
或者,要获得一个干净的 type MixedAType=MyMixinY & X,你可以选择在混入中返回正确的构造函数类型:
type Constructor<T = {}> = new(...args: any[]) => T;
interface MyMixinY {
doY()
}
function MixinY<T extends Constructor>(BaseClass: T)
: Constructor<MyMixinY> & T {
return <any> class Y extends BaseClass implements MyMixinY {
doY() {
console.log("in Y");
}
}
}
const MixedA = MixinY(class X {
doX() {
console.log("in X");
}
});
function getReturnType<R>(fn: (new(...args: any[]) => R)): R {
return {} as R;
}
const dummy = getReturnType(MixedA);
type MixedAType = typeof dummy; // now is `type MixedAType = MyMixinY & X`
const mixedA: MixedAType = new MixedA();
mixedA.doX();
mixedA.doY();
