Home > Mobile >  What is the typescript type of a constructor function?
What is the typescript type of a constructor function?

Time:03-31

What is the Typescript type of a constructor function?

Here is an example of what I mean which throws this warning:

TS2507: Type 'Function' is not a constructor function type.

What type do I need to define clazz as here ?

class A {
 foo() {console.log("bar")};
}

console.log(typeof A);
// function

function Factory(clazz: Function) : any {
    class B extends clazz {
        // Type 'Function' is not a constructor function type.
    }
    return B;
}

class Foo extends Factory(A) {}

new Foo().foo();

If I suppress the TS warning this code will execute and print out the expected result of bar

CodePudding user response:

We will use a construct signature:

type Constructable = { new (...args: any[]): any; };

function Factory(clazz: Constructable): Constructable { 
    class B extends clazz {

    }
    return B;
}

But this is not very good as a return type. Ideally it should at least return the class that was passed in:

function Factory<T extends Constructable>(clazz: T): T {
    class B extends clazz {

    }
    return B;
}

Going further, we could also annotate the return type as T & { ... } to match the class that is returned, too.

Playground

  • Related