TypeScript:类

时间:2016-10-31 23:04:13

标签: typescript mixins

我只是想创建一个以类为参数的函数:

const mixin = (traits: Object) =>
  (baseClass: class) => { // What type to put here?
    Object.assign(baseClass.prototype, traits)
    return baseClass
  }

但是我不知道我要用什么类型来指定我正在使用构造函数。

1 个答案:

答案 0 :(得分:4)

您可以使用泛型返回正确的类构造函数:

const mixin = (traits: any) =>
    <T>(baseClass: { new (): T }) => {
        Object.assign(baseClass.prototype, traits);
        return baseClass;
    }

class A {}

let o = mixin({})(A); // typeof o is new () => A
let a = new o(); // typeof a is A

code in playground