kube kube - 6 months ago 50
TypeScript Question

TypeScript: Type of a class

I simply want to create a function that takes a class as argument:

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

But I don't know what type I have to put to specify I'm working with a Constructor Function.


You can use generics to return the right class constructor:

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)