2017-05-04 92 views
1

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其中创建并返回一个实例

回答

2

你得到这个错误是因为T是一个类型,而不是class

在打字稿一个class有这样的签名:new(...args: any[]) => any,你可以调用的Object.create就可以了,因为T是不是在你的函数变量你不能做这样的事情。

达到你想要做什么,你必须将自己class传递作为参数:

private static _parseT<T extends Constructable>(clazz: new(...args: any[]) => any, obj : any) : T { 
    let instance = <Constructable>new clazz(); 
    instance.copy(obj); 
    return <T>instance; 
} 

这样,那将是唯一接受的clazz是构建你的类型的人。

你可以在我最近在github(不是一个角度的项目,但你的问题是一个纯打字稿问题)做的事情的例子。

的示例性呼叫此功能:

let FooInstance = this._parseT<FooClass>(FooClass, myObj); 

这里,第一FooClass是类型,而一个Seconde系列冷藏箱到class本身。

由于您无法在运行时获得类型的类,因此它是您从类型构造类的唯一解决方案。

+0

其synatictically不正确。 clazz:new(... args:any []):T是错误的。 试图将它转换为clazz:new(... args:any [])=> T然后我也有编译错误 –

+0

哦对不起,我会修复这个错字,但第二个应该编译... OO(检查我链接的例子,它完美地编译) – Supamiu

+0

'new'(... args:any [])=> T'012'''''''''args:any [])=> T'不能分配给T类型 –