Open xaviergonz opened 4 years ago
I only read the first half of the description. However, does this solve your issue?
function createDynamicClass(): { new<T>(): {x: T}} {
// implementation detail doesn't matter
return null as any;
}
// without generics on the main class all is fine
class C2<T> extends createDynamicClass()<T> {
setX(x: T) {
this.x = x
}
}
// all good
const c2 = new C2()
c2.x = 20
c2.setX(30)
Hi, thanks for looking at it! Sadly it doesn't. I just changed the theoretical examples so they better match the use cases. The real case relies on type inference for the dynamic class function to work.
It would be very helpful if TypeScript supported this feature. Is there any interest and/or progress in implementing it? Any open questions?
I am facing this problem too.
Is it still up to debate ?
I'm facing it in the simple legacy case class MyClass<T> extends MyParent<T> {...
Search Terms
Base class expressions cannot reference class type parameters
Suggestion
Right now it is possible in Ts to generate base classes dynamically (via a function):
And it is also possible to reuse a generic when the base class is a "pure" class with a generic type:
However, currently it is impossible for a function that generates a dynamic class to re-use the type from the child class:
There's a (somehow ugly) workaround, which is encapsulating the generation of the child class in a function and use its result:
But it is quite ugly, and results in a new class being generated for each generic when it is not actually needed (just for the typings).
The proposal is basically to lift this constraint and allow it to be used (like it can be easily used for pure classes).
Use Cases
Right now in mobx-keystone it uses such a pattern (a function that generates a dynamic base class) to generate models:
but in order to support generics, rather than just doing this:
users have to resort to a factory pattern like this:
which is far from ideal (and this is just to get typings right).
Examples
See above
Checklist
My suggestion meets these guidelines:
It wouldn't since it is lifting a constraint that currently is just not allowed, so no current code can be using it.
The runtime behaviour would be exactly the same, it just addresses a typings problem.