0

我想为抽象类实现的实现创建一个mixin

所以我有一个抽象类

abstract class A {
    doStuff(): void {
        this.doMoreStuff();
    }

    abstract doMoreStuff(): void;
}

以及我想要一个mixin的实现:

class B extends A {
    doMoreStuff(): void {
        console.log(3 + 5);
    }
}

例如,这个 mixin 在工作完成时会做一些额外的报告:

type Constructor<T> = new (...args: unknown[]) => T;

function WorkReporter<T extends A, TBase extends Constructor<T>>(Base: TBase): TBase {
    return class W extends Base {
        doStuff(): void {
            console.log("Does stuff");
            super.doStuff();
        }

        doMoreStuff(): void {
            console.log("Does more stuff!");
            super.doMoreStuff();
        }
    };
}

最终,使用了 mixin:

const ReportedWork = WorkReporter(B);
new ReportedWork().doStuff();

但是,我无法让它工作。我找不到一种方法来为 A 本身而不是为 A 的任何实现创建 mixin。对于 mixin,我得到:

Class 'W' incorrectly extends base class 'T'.
  'W' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'A'.

对于 mixin 中的 doMoreStuff 调用,我得到:

Abstract method 'doMoreStuff' in class 'A' cannot be accessed via super expression.

我怎样才能做到这一点?我需要一个调用抽象超类的实现并扩展其功能的mixin。

4

1 回答 1

0

代替

super.doMoreStuff();

尝试

(Base.prototype as A).doMoreStuff?.call(this);

为什么不只是

function WorkReporter<TBase extends Constructor<A>>(Base: TBase): TBase { ...
于 2020-12-05T15:11:24.800 回答