【发布时间】:2021-06-18 08:00:28
【问题描述】:
我应该如何修改WithArea函数的areaCalculator的泛型类型参数U,以扩展当前MixinFactory实例的基类?
type Constructor<T> = new (...args: any[]) => T;
interface IArea {
readonly area: number;
}
class MixinFactory<T extends Constructor<Shape>> {
constructor(public Superclass: T) {}
WithArea(areaCalculator: <U extends Shape & IArea>(ctx: U) => number) {
return new MixinFactory<T & Constructor<IArea>>(class extends this.Superclass implements IArea {
get area(): number {
return areaCalculator(this);
}
})
}
}
class Shape {}
class RectRaw extends Shape {
constructor(
public x: number,
public y: number,
public w: number,
public h: number) {
super();
}
}
const Rect = new MixinFactory(RectRaw).WithArea(ctx => {
return ctx.w * ctx.h;
}).Superclass;
const rect = new Rect(10, 10, 20, 20);
console.log(rect.area);
【问题讨论】:
-
我花了一段时间才理解你的代码,相当复杂)
标签: typescript mixins typescript-generics