Im使用typescipt 2. 编写一些解析器方法,它从服务器接收模型并将其转换为我可以使用的实例。Typescript(Angular2)通用构造函数工厂
代码:
export interface Constructable {
copy(other : any) : void;
}
//in my Convert class which converts server responses to model
private static _parseT<T extends Constructable>(obj : any) : T {
let instance = Object.create(T); // the row of the compile-time error
instance.constructor.apply(instance);
instance.copy(obj);
return instance;
}
,并让我们假设我有以下类
export class Foo implements Constructable {
private test : string = null;
public copy(other:any) : void {
this.test = other.test;
}
}
我有一个编译时错误
找不到名字牛逼
现在,我确定它不是语法,但我无法找到。
清除事情。这是使用率的样子:
public static ParseFoo(data: any) : Foo{
return Convert._parseT<Foo>(data.mResult); // data is a server response object
}
注意
虽然有些工厂模式将解决这个问题,我真的想留在Copy
方法,而不是一些Generate
其中创建并返回一个实例
其synatictically不正确。 clazz:new(... args:any []):T是错误的。 试图将它转换为clazz:new(... args:any [])=> T然后我也有编译错误 –
哦对不起,我会修复这个错字,但第二个应该编译... OO(检查我链接的例子,它完美地编译) – Supamiu
'new'(... args:any [])=> T'012'''''''''args:any [])=> T'不能分配给T类型 –