Having a problem with Typescript's Generics where the type is undefined in the scope of the generic function or class. I can't find any documentation on this though I would assume it is by design. Is there a way to achieve what I am trying to, type-safely?
function test<T>() {
return new T();
}
class TestClass<T> {
public build(): T {
return new T();
}
}
Link to Play:
TypeScript generics (unlike other languages like C#) are compile time only. So you cannot use them in runtime positions eg new T
.
Is there a way to achieve what I am trying to, type-safely
Pass the constructor explicitly . eg
class TestClass<T> {
public build(x:{new ():T}): T {
return new x();
}
}
Here x:{new ():T}
I am saying that x
is something that when called with new
gives an instance of T
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.