Reputation: 3026
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?
Upvotes: 14
Views: 10682
Reputation: 2367
I also got this error when my type was wrapped in a module, and I was calling new on the module rather than the type. This Q&A helped me rule out some things, and then I came to the realization it was something quite silly after a long day of programming.
Upvotes: -1
Reputation: 221392
I'd write it this way (with generics as a bonus):
function instantiate<T>(ctor: { new(...args: any[]): T }): T {
Upvotes: 19