简体   繁体   English

TypeScript:用于实现抽象 class 的 Mixin

[英]TypeScript: Mixin for implementation of abstract class

I would like to create a mixin for the implementation of an abstract class implementation我想为抽象 class 实现的实现创建一个 mixin

So I have an abstract class所以我有一个抽象的 class

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

    abstract doMoreStuff(): void;
}

and an implementation for which I want a mixin:以及我想要一个mixin的实现:

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

This mixin, for example, does some additional reporting when work is done:例如,这个 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();
        }
    };
}

And eventually, the mixin is used:最终,使用了 mixin:

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

However, I can't get this to work.但是,我无法让它工作。 I can't find a way how to create a mixin not for A itself, but for any implementation of A. For the mixin, I get:我找不到一种方法来为 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'.

And for the doMoreStuff call within the mixin, I get:对于 mixin 中的 doMoreStuff 调用,我得到:

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

How can I achieve this?我怎样才能做到这一点? I need a mixin which calls the implementation of an abstract super class and extending its functionality.我需要一个 mixin,它调用抽象超级 class 的实现并扩展其功能。

instead of代替

super.doMoreStuff();

try尝试

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

and why not just为什么不只是

function WorkReporter<TBase extends Constructor<A>>(Base: TBase): TBase { ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM