I have a class that takes a generic:
abstract class Base<P extends SomeType = SomeType> {
// ...
}
And a class that extends it:
class A extends Base<SomeTypeA> {
// ...
}
Its hard to describe, but basically I'm wondering if its possible with typescript to know "What is the type that class A extended Base with?"
Something like
type PropType = ExtendedGeneric<A> // SomeTypeA
CodePudding user response:
You can use a conditional type to extract the type that was passed to Base
type ExtendedGeneric<T extends Base<any>> = T extends Base<infer P> ? P: never
type PropType = ExtendedGeneric<A> // SomeTypeA
You can read more about conditional types here
CodePudding user response:
You can add this method in your base:
abstract getType(): Constructible<Type>;
and you have to define an interface Constructible:
export interface Constructible<T> {
new (data): T;
}
then in your class A implement the method:
class A extends Base<SomeTypeA> {
getType(): Constructible<SomeTypeA> {
return SomeTypeA;
}
// ...
}