Search code examples
typescript

How to extract the generic parameter from a type?


Say I have a type like React.ComponentClass<Props> and I want to reference the Props part but it is unnamed in my current context.

To illustrate:

const x = makeComponent(); // typeof x = React.ComponentClass<Something>

In this situation, I can use typeof x but that doesn't give me direct access to the Something type.

What I want is something like this:

type GetPropsType<C extends React.ComponentClass<P>> = P

So that I can extract Something with the type GetPropsType<typeof x>

Is there anything equivalent?


Solution

  • You can use infer:

    type TypeWithGeneric<T> = T[]
    type extractGeneric<Type> = Type extends TypeWithGeneric<infer X> ? X : never
    
    type extracted = extractGeneric<TypeWithGeneric<number>>
    // extracted === number
    

    Playground