首页 > 解决方案 > 如何提取作为道具传递给React函数组件的属性的嵌套类型

问题描述

如果我为功能组件定义了一个接口,比如说

MyFuncComp.tsx

import React from 'react'

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

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

我在另一个组件中使用该组件

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} /></>
}

如何提取函数组件中定义的属性的类型,以便我也可以使用相同的类型MyPage.tsx

我知道我可以完全导出/导入接口,但我想避免这种情况。

标签: reactjstypescriptreact-functional-componentreact-typescript

解决方案


MyFuncComp我可以从以下中的功能组件推断类型MyPage.tsx

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} /></>
}

参考答案thisthis


推荐阅读