New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Creating instance of generic types #2037
Comments
You have to remember what In our type system, we require a value to have a construct signature in its type to be interface NoParamConstructor<T> {
new (): T;
}
class View<T> {
data: T;
constructor(ctor: NoParamConstructor<T>) {
this.data = new ctor();
}
}
class MyData {
user: string
}
class MyView extends View<MyData> {
constructor() {
// This will work because 'MyData' is also an entity
// in the value space.
super(MyData);
}
}
var view = new MyView(); Hope that helps! |
Thanks for the answer - I'm aware of the workaround you mentioned. However I still think you could solve this "lexically" - just by replacing type parameter with original type definition in generate JS. Anyway - thanks for fast response:) |
You have the exact same situation in C#. Making However, in C#, you have @DanielRosenwasser, could we have any of that love in TypeScript? |
Even if not, TypeScript loves you. 😄
Actually, @AlicanC, you can specify a The difference is that in C#, there is a straightforward correspondence between types and their constructors. We're not really blessed with that benefit. In my example, I've done something loosely similar, except you have to explicitly pass the constructor function (in this case If you think about the example though, we've sort of just replaced the type argument with a regular argument, which is not much worse really. |
Hello,
Why can't I do following?
In above case TypeScript compiler knows lexically that T is MyData, so why it can't exchange new T() with new MyData() ?
Thanks:)
The text was updated successfully, but these errors were encountered: