我试图将一个类作为参数传递给某个函数,它将实例化该类并返回它.这是我的代码:
module A.Views {
export class View { ... }
}
module A.App {
export class MyApp {
...
registerView(viewKlass:A.Views.View):void
{
var test = new viewKlass;
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我试图编译这个时,我得到:
(...): Value of type 'Views.View' is not newable.
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
如果newable类型值是对象构造函数,我如何在运行时传递构造函数?
如此处所述:使用 TypeScript 声明类类型(将类作为参数传递)我可以将类类型作为参数传递。
有一个问题:
export namespace customCommand {
export class Command {
public constructor(parameter?: any) {
}
}
export function register(command: typeof Command) {
new command()
}
}
Run Code Online (Sandbox Code Playgroud)
当我这样做时
customCommand.register(Map)
Run Code Online (Sandbox Code Playgroud)
或者
customCommand.register(Object)
Run Code Online (Sandbox Code Playgroud)
没有错误。我知道typeof Command
并且typeof Map
两者返回相同的结果。
但我怎样才能保护这个并只传递Command
类型呢?