使用 TypeScript 混合模式?

mixin pattern with TypeScript?

我读过这篇文章。 https://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/

这里是文章JavaScript的原始代码:

class MyClass extends mix(MyBaseClass).with(Mixin1, Mixin2) {
  /* ... */
}

let mix = (superclass) => new MixinBuilder(superclass);

class MixinBuilder {
  constructor(superclass) {
    this.superclass = superclass;
  }

  with(...mixins) { 
    return mixins.reduce((c, mixin) => mixin(c), this.superclass);
  }
}

我想知道如何在 typescript 中创建这样一个 mixin 实用程序助手,以便我可以进行类型匹配和静态代码分析。

我已经尝试了几个小时...但是如果不使用一些 any 类型就无法完成它,如果我使用 any 我会错过所有类型提示,这不是我想要的想要。

您可以使用链接,否则所有 Mixin 都必须使用泛型具有相同的 return 签名:

interface Ctor<T = NonNullable<any>> {
    new(...params: any[]): T;
}

interface MixIn<Superclass extends Ctor, Extension extends Ctor> {
    (ctor: Superclass): Superclass & Extension;
}
function mix<T>(superclass: Ctor<T>) {
    return new MixinBuilder(superclass);
}

interface Mixed<T extends Ctor> {
    with<K extends Ctor>(mixin: MixIn<T, K>): Mixed<ReturnType<MixIn<T, K>>> & ReturnType<MixIn<T, K>>;
}

class MixinBuilder<T extends Ctor> {
    superclass: T;
    constructor(superclass: T) {
        console.log(superclass);
        this.superclass = superclass;
    }

    with<K extends Ctor>(mixin: MixIn<T, K>): Mixed<ReturnType<MixIn<T, K>>> & ReturnType<MixIn<T, K>>  {
        const mixed = mixin(this.superclass);
        return class extends mixed {
            static with<K extends Ctor>(mixin: MixIn<typeof mixed, K>) {
                return new MixinBuilder(mixed).with(mixin);
            }
        } as any;
    }
}

Playground