TypeScript中如何向接收对象联合类型的React组件传递动态props?
问题原因
你将联合类型Props解构为identifier和attributes两个独立变量后,TypeScript 无法跟踪两个变量之间的类型关联。即使你判断了identifier的具体值,也无法自动收窄attributes的类型,导致TS始终认为attributes是{id: string} | {src: string}的联合类型,传给对应组件时就会报属性缺失的错误。
解决方案
方案1:不解构props,保留类型关联(最推荐,无额外类型断言,完全类型安全)
直接使用完整的props对象做判断,利用TypeScript对判别式联合的自动收窄能力,TS会自动根据identifier的值推导对应attributes的类型:
type Props = { identifier: "YouTube"; attributes: { id: string }; } | { identifier: "Figure"; attributes: { src: string }; }; // 先给子组件加上正确的props类型 const YouTube = ({ id }: { id: string }) => <p>{id}</p>; const Figure = ({ src }: { src: string }) => <p>{src}</p>; const Shortcode = (props: Props): JSX.Element => { switch (props.identifier) { case "YouTube": // TS自动推断props.attributes为 {id: string} 类型 return <YouTube {...props.attributes} />; case "Figure": // TS自动推断props.attributes为 {src: string} 类型 return <Figure {...props.attributes} />; } };
方案2:使用类型断言(适合不想修改解构写法的场景)
如果一定要提前解构props,可以手动给attributes做类型断言,告诉TS你确认当前场景下的attributes类型:
const Shortcode = ({ identifier, attributes }: Props): JSX.Element => { switch (identifier) { case "YouTube": return <YouTube {...attributes as { id: string }} />; case "Figure": return <Figure {...attributes as { src: string }} />; } };
注意:该方案需要你手动保证类型匹配,后续如果Props类型修改需要同步更新断言内容,存在一定的维护成本。
方案3:映射表封装(适合后续会新增大量组件的场景,扩展性更强)
如果后续需要新增更多类型的短码组件,可以通过映射表统一维护,无需写switch分支,新增组件只要更新映射表即可,类型会自动推导:
// 维护identifier和对应组件的映射关系 const componentMap = { YouTube: ({ id }: { id: string }) => <p>{id}</p>, Figure: ({ src }: { src: string }) => <p>{src}</p>, } as const; // 自动生成Props类型,无需手动写联合类型 type Props = { [K in keyof typeof componentMap]: { identifier: K; attributes: React.ComponentProps<typeof componentMap[K]>; } }[keyof typeof componentMap]; const Shortcode = (props: Props): JSX.Element => { const Component = componentMap[props.identifier]; return <Component {...props.attributes} />; };
内容的提问来源于stack exchange,提问作者Lucas Caton
相关产品推荐
相关产品推荐

