ysfaran
ysfaran

Reputation: 6952

How to get type of one specific prop of a react component?

Imagine you import a React.Component (let's call it Foo) from any library (e.g. from node_modules). Now you want to extract the type of a prop (let's call it complexProp) from Foo, so you can use it elsewhere.

Example

Foo.tsx:

interface FooProps <P /*some generic stuff here*/> {
    complexProp: /*some super weird type you can not simply copy*/;
}

export class Foo extends React.Component<FooProps> {
    //...
    public render(){
        //...
        lookAtComplexProp(this.props.complexProp)
        //...
    }
}

function lookAtComplexProp(complexProp: /* I need the type of Foo.props.complexProp here*/) {
    //...
}

Upvotes: 1

Views: 1132

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

You can use a type query to get the type of any property of the interface. A simple type query has the form Type['PropName']. Instead of 'PropName' you can also use any string literal type or a union of them all representing keys of the target type. In your case it could look something like this:

function lookAtComplexProp<P /*copy constraint here*/>(complexProp: FooProps<P>['complexProp']){
    //...
}

Or if you already know for what P you want the complexProp:

function lookAtComplexProp(complexProp: FooProps<number /* or other type */ >['complexProp']){
    //...
}

Or if your interface has a default generic parameter you can omit the type parameter:

interface FooProps <P = number> {
    complexProp: { complexStuff: P};
}

function lookAtComplexProp(complexProp: FooProps['complexProp']){
    //...
}

You can also define a type alias for it just as you would for any type. But again depending on what you want to do there are options:

type myComplexType<P /*copy constraint here*/> = FooProps<P>['complexProp'] // you want the type alias to be generic so can get the type for any P.
type myComplexType = FooProps<number>['complexProp'] // you want complexProp type for a specific type argument
type myComplexType = FooProps['complexProp'] // FooProps has a default type argument

Upvotes: 1

Related Questions