React TypeScript中如何为forwardRef组件传入动态泛型类型
解决方案
你不能直接在const变量声明时附加泛型参数,需要先定义泛型的函数类型,再将forwardRef返回的结果断言为该类型。
核心改动代码
首先新增/修改泛型组件类型定义:
// 定义带泛型的组件类型,泛型参数绑定在函数层面 type FinalComponentType = <GenericType extends 'a' | 'b'>( props: PropsWithStandardRef<GenericType> ) => JSX.Element;
然后替换原来错误的FinalComponent定义:
const FinalComponent = forwardRef< HTMLParagraphElement, PropsWithStandardRef<'a' | 'b'> >(({ value }, ref) => { return <CoreComponent forwardedRef={ref} value={value} /> }) as FinalComponentType;
验证使用
修改后即可按你预期的方式使用,无TS报错:
// 正常工作,value会被限定为'b'类型 const ExampleUsage = () => <FinalComponent<'b'> value="b" /> // 传入错误value会触发TS报错:<FinalComponent<'b'> value="a" />
原理说明
- TypeScript语法不支持
const 变量名<泛型参数>的写法,泛型参数只能定义在函数、接口、类型别名上。 - React的
forwardRef默认返回的组件类型不会保留泛型能力,因此必须通过类型断言,将其手动标注为泛型函数类型,才能在组件使用时主动传入泛型参数。
该写法可直接扩展到复杂业务场景,不受props复杂度影响。
内容的提问来源于stack exchange,提问作者Daniel Tonon
相关产品推荐
相关产品推荐

