Home > Back-end >  Get the generic type of another type
Get the generic type of another type

Time:12-11

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.

CodePudding user response:

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

  • Related