How to extract nested type of an attribute passed as props to a React function component

Viewed 112

If I have an interface defined for a function component, say

MyFuncComp.tsx

import React from 'react'

interface MyFuncCompProps {
    x: string
    y: number
    z: Array<ComplexType>
}

export function MyFuncComp(props: MyFuncCompProps) {
    return <>...</>
}

And I use the component in another component

MyPage.tsx

import React from 'react'
import {MyFuncComp} from 'MyFuncComp.tsx'

export function MyPage(){
    const [x, setX] = React.useState()
    const [y, setY] = React.useState()
    const [z, setZ] = React.useState()
    return <><MyFuncComp x={x} y={y} z={z} /></>
}

How can I extract the type of the attributes defined within the function component so that I may use the same type in MyPage.tsx as well?

I understand that I can export/import the interfaces all over, but I want to avoid that.

1 Answers

I can infer the types from the functional component MyFuncComp in MyPage.tsx This is how:

import {MyFuncComp} from 'MyFuncComp.tsx'
const InferredTypes = React.ComponentProps<typeof MyFuncComp>

export function MyPage(){
    const [x, setX] = React.useState<InferredTypes['x']>()
    const [y, setY] = React.useState<InferredTypes['y']>()
    const [z, setZ] = React.useState<InferredTypes['z']>()
    return <><MyFuncComp x={x} y={y} z={z} /></>
}

Referenced from answers this and this

Related