I think I can do something like this to create a new instance of a Generic in TypeScript:
class Tree<T extends SomeInterface> {
constructor(private elementType: {new(): T}) {
}
public Grow() {
var newElement: T = new this.elementType();
// ...
}
}
But is there any way to let TypeScript know that a Generic has a new()
? In other words, is there any way to get something like this to work?
class Tree<T extends SomeInterface> { // <-- Modify the constraint?
public Grow() {
var newElement: T = new T();
// ...
}
}
But is there any way to let TypeScript know that a Generic has a new()? In other words, is there any way to get something like this to work?
Not Exactly. Reason is that you still need to pass in the entity that will New up the object for you. You can't just use the compile time constraint<T>
as a runtime 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();
// ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With