本文介绍了具有TypeScript中通用类型的ES6 Mixin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在TypeScript中使用ES6 Mixin。我所拥有的如下,它与 BaseClass 完美搭配。

I'm trying to use ES6 Mixin in TypeScript. What I have is as below, and it works perfect with BaseClass.

class BaseClass {
    public foo() {}
};

interface IMyMixin {
    foo2();
}

let MyMixin = (superclass: typeof BaseClass) => class extends BaseClass implements IMyMixin {
    public foo2() {}
}

class MyBaseClass extends MyMixin(BaseClass) {

}

但是我不能将 MyMixin 应用于 BaseClass ;同时,我也不能使mixin通用。

However I can't apply MyMixin on derived class from BaseClass; Meanwhile, I can't make mixin generic either.

有没有办法使它同时适用于 BaseClass DerivedClass

Is there a way to make it work for both BaseClass and DerivedClass?

class DerivedClass extends BaseClass {
    public bar() {}
}

class MyDerivedClass extends MyMixin(DerivedClass) {
    public something() {
// Compile Error: Property 'bar' does not exist on type 'MyDerivedClass'
        this.bar();
    }
}

// Compile Error: 'T' only refers to a type, but is being used as a value here.
let MyMixin = <T extends BaseClass>(superclass: typeof T) => class extends T implements IMyMixin {
    public foo2() {}
}


推荐答案

我从 TypeScript / PR#13743 ,并使用@Maximus的注释对其进行优化。

I've found solution from TypeScript/PR#13743, and optimized it with comment from @Maximus.

这段代码有效。原因是,在 MyMixin 中, T 应该是 Class

This piece of code works. The reason is, in MyMixin, T should be a Class (i.e. a constructor), not a type.

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

class BaseClass {
    public foo() { }
};

interface IMyMixin {
    foo2();
}

// `implements IMyMixin` is optional.
let MyMixin = <T extends Constructor<BaseClass>>(superclass: T) => class extends superclass implements IMyMixin {
    public foo2() { }
}

class DerivedClass extends BaseClass {
    public bar() {}
}

class MyDerivedClass extends MyMixin(DerivedClass) {
    public something() {
        this.bar();
        this.foo();
        this.foo2();
    }
}

这篇关于具有TypeScript中通用类型的ES6 Mixin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!