kube kube - 1 year ago 149
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.

Answer Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download