我有一个函数,用给定的构造函数实例化一个对象,传递任何参数.
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.');
}
}
Run Code Online (Sandbox Code Playgroud)
它是这样使用的:
export class Thing {
constructor() { ... }
}
var thing = instantiate(Thing);
Run Code Online (Sandbox Code Playgroud)
这有效,但编译器抱怨每个new ctor
实例,说Cannot use 'new' with an expression whose type lacks a call or construct signature.
.应该ctor
有什么类型?
Rya*_*ugh 19
我这样写(以泛型作为奖励):
function instantiate<T>(ctor: { new(...args: any[]): T }): T {
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10257 次 |
最近记录: |