How to get the generic type of class in TypeScript

Issue

I need to try and get the generic type passed into a class in TypeScript.

See my example below, I initialize my class with type 'hello' | 'goodbye'

I then want to create a function with has the parameter of the type passed into the original class.

Is this possible?

class MyTestClass<T> {
  doSomething = (myType: T, count: number) => {
    // ...
  }
}

const myTest = new MyTestClass<'hello' | 'goodbye'>()

const myNewMethod = (subType: typeof myTest) => {
  // I want subType to be 'hello' | 'goodbye'
}

Solution

You can use conditional types wit the infer keyword to extract the U from MyTestClass<U>

type subType = typeof mytest extends MyTestClass<infer U> ? U : never;

Here, if myTest is any kind of MyTestClass<X>, then subType will be the X, otherwise it will be never (which won’t ever happen since your myTest is explicitly a MyTestClass.

Answered By – CollinD

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.