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 the generic type of another type

Suppose I have this :

const sub = new Subject<{  id: string; value: string; }>();

How can I get the generic type given to the Subject ?

const item: ??? = { id: '1', value: 'value' };

I am aware that I can declare an interface, or simply give the exact same type to my item. What I would like to know is if there is a way to get the generic type of another type in a more global way.

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

>Solution :

You can infer the generic type:

const sub = new Subject<{  id: string; value: string; }>();
type Unwrap<T extends Subject<unknown>> = T extends Subject<infer K> ?  K : never;
type Item = Unwrap<typeof sub>;
var item: Item = {
  id: '1',
  value: '2'
}

Playground link

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