Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Cannot use 'new' with an expression whose type lacks a call or construct signature

Tags:

typescript

I have a function that instantiates a object with a given constructor, passing along any arguments.

function instantiate(ctor:Function):any {
    switch (arguments.length) {
        case 1:
            return new ctor();
        case 2:
            return new ctor(arguments[1]);
        case 3:
            return new ctor(arguments[1], arguments[2]);
        ...
        default:
            throw new Error('"instantiate" called with too many arguments.');
    }
}

It is used like this:

export class Thing {
    constructor() { ... }
}

var thing = instantiate(Thing);

This works, but the compiler complains about each new ctor instance, saying Cannot use 'new' with an expression whose type lacks a call or construct signature.. What type should ctor have?

like image 233
alekop Avatar asked Jul 04 '15 19:07

alekop


1 Answers

I'd write it this way (with generics as a bonus):

function instantiate<T>(ctor: { new(...args: any[]): T }): T {
like image 165
Ryan Cavanaugh Avatar answered Sep 19 '22 13:09

Ryan Cavanaugh