1

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*/) {
    //...
}
  • Is this somehow possible?
  • Exspecially, is this possible without knowing anything about the code behind Foo? In other words, is a syntax like type complexPropType = Foo.complexProp.getType(); possible?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to save the type, so you don't have to write it like this always? type myComplexType = /* set type once */; and then only reference myComplexType everywhere you need it.
@Truntle sure, you can define a type alias for any type, edited the anser with the new info

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.