我想要一个像以下一样的功能:
createEntity<TEntity>(): TEntity {
return new TEntity();
}
Run Code Online (Sandbox Code Playgroud)
在C#中我们可以写:
void TEntity CreateEntity<TEntity>() where TEntity : new()
Run Code Online (Sandbox Code Playgroud)
我怎么能在TypeScript中做到这一点?
tos*_*skv 14
手册中显示的与此类似的方法的唯一方法是将要初始化的类作为参数发送到工厂方法,并使用new关键字描述它的构造函数.
function factory<T>(type: { new (): T }): T {
return new type();
}
class SomeClass { }
let result = factory(SomeClass);
Run Code Online (Sandbox Code Playgroud)
该结果将是类型SomeClass的的.
将根据工厂方法中定义的接口对类的构造函数进行类型检查.
如果要初始化一个在其构造函数中带有参数的类,则必须在给出工厂方法的接口中指定该类.
function factory<T>(type: { new (name: string): T }, val: string): T {
return new type(val);
}
class SomeClass {
constructor(name: string) { }
}
let a = factory(SomeClass, 'John Doe');
Run Code Online (Sandbox Code Playgroud)
小智 5
这已经回答了这里的堆栈溢出。为了能够使用泛型创建新的类,您需要确保类型支持实例化。
您可以使用这种方法轻松支持较少参数的构造函数,但是对于需要参数的构造函数,它将变得不那么有用,因为您的creatEntity方法应该在创建新实例时必须接受这些参数的值并传递给构造函数,如您所见每种类型都可以具有自己的构造函数签名。
class ObjectCreator{
static createEntity<TEntity>(type:{new():TEntity;}):TEntity{
return new type();
}
}
class Person{
firstName:string;
lastName:string;
constructor(){
this.firstName = "TestFirstName";
this.lastName = "TestLastName";
}
}
var person: Person = ObjectCreator.createEntity(Person);
alert(person.firstName);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12459 次 |
| 最近记录: |