Home > Mobile >  Get the <T> type in Typescript
Get the <T> type in Typescript

Time:07-18

For example in my case I need to reuse the type of a component in React (React.FC) but I want it with optionals props by using Partial<T>.

Is there a way to "get" the Generic <T> from that component type (type TypeTargetComponent = React.FC<T>) ? I would like to do something like : React.FC<Partial<XXXX<typeof TargetComponent>>> where XXXXis the "method" to get what I want.

CodePudding user response:

type ExtractPropsType<T> = T extends React.FC<infer Type> ? Type : never; 

This should work if you type typeof TargetComponent

CodePudding user response:

You can use the infer keyword.

Something like this should work:

Updated the answer to include example and fixed the type inferrence issue.

type FC<T> = { data: T }

type InferredValueOf<Comp extends FC<any>> = Comp extends FC<infer T> ? T : never

type Derived<TargetComponent> = TargetComponent extends FC<any> ? FC<Partial<InferredValueOf<TargetComponent>>> : never

type TestType = Derived<FC<{ testValue: "value" }>>

const test: TestType = {
    data: {
        // testValue is optional now
    }
}
  • Related