能否基于传入高阶组件(HOC)的组件推断Props类型?
可以自动推断Props类型,无需手动指定泛型参数
你完全可以让TypeScript自动根据传入的组件推断所需的Props类型,不需要每次调用都手动声明<HomeProps>。
基础自动推断写法
你的HOC已经使用了泛型,只需要去掉调用时的手动泛型指定,TypeScript会自动从传入的Component参数推断出TOriginalProps的类型:
interface HomeProps { date: number; greeting?: string; } function Home(props: HomeProps) { const { date, greeting } = props; return ( <div> date: {date}, greeting: {greeting} </div> ); } function GreetingHOC<TOriginalProps>( Component: React.ComponentType<TOriginalProps>, props: TOriginalProps ) { const injectedProp = 'hello'; return <Component greeting={injectedProp} {...props} />; } // 调用时无需手动指定<HomeProps>,TypeScript自动推断 const compProps = { date: +new Date(), }; GreetingHOC(Home, compProps); // 正常通过类型检查
更严谨的类型优化(排除注入的Props)
因为你的HOC会注入greeting属性,所以调用时其实不需要传入这个属性(哪怕它是可选的)。可以通过Omit工具类型让传入的props自动排除掉被注入的属性,避免冗余传参:
function GreetingHOC<TOriginalProps>( Component: React.ComponentType<TOriginalProps>, // 传入的props排除掉greeting属性 props: Omit<TOriginalProps, 'greeting'> ) { const injectedProp = 'hello'; return <Component greeting={injectedProp} {...props} />; } // 此时如果传入greeting会触发类型错误,更符合逻辑 const compProps = { date: +new Date(), // greeting: 'hi' // 这里会报错,因为HOC已经注入了该属性 }; GreetingHOC(Home, compProps);
关于你提到的typeof Component.props写法
这种写法不适用于函数组件(因为函数组件没有props静态属性),类组件虽然有defaultProps,但也不存在直接的props属性。所以正确的方式还是通过泛型让TypeScript自动推断组件的Props类型,这也是React + TypeScript中HOC的标准写法。
内容的提问来源于stack exchange,提问作者Amir
相关产品推荐
相关产品推荐

