Eri*_*ric 5 generics typescript
我想我可以做这样的事情来在 TypeScript 中创建一个新的 Generic 实例:
class Tree<T extends SomeInterface> {
constructor(private elementType: {new(): T}) {
}
public Grow() {
var newElement: T = new this.elementType();
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
但是有什么方法可以让 TypeScript 知道 Generic 有一个new()? 换句话说,有没有办法让这样的事情起作用?
class Tree<T extends SomeInterface> { // <-- Modify the constraint?
public Grow() {
var newElement: T = new T();
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
但是有没有办法让 TypeScript 知道 Generic 有 new() 呢?换句话说,有什么办法可以让这样的事情发挥作用吗?
不完全是。原因是您仍然需要传入将为您新建对象的实体。您不能仅将编译时间约束用作<T>运行时new T。
interface SomeInterface{
}
interface SomeInterfaceConstructor<T extends SomeInterface>{
new (): T;
}
class Tree<T extends SomeInterface> {
constructor(private elementType: SomeInterfaceConstructor<T>) {
}
public Grow() {
var newElement = new this.elementType();
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1974 次 |
| 最近记录: |