Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get generic type used to extend a class

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?"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Something like

type PropType = ExtendedGeneric<A> // SomeTypeA

>Solution :

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

Playground Link

You can read more about conditional types here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading