TypeScript导出函数报错:类型'string | IconProps'无法赋值给'string | undefined'
解决TypeScript导出函数时的类型不匹配问题
报错核心原因:你的组件Props中icon字段类型为string | IconProps,但返回时传递的icon属性仅接受string | undefined类型。当icon是IconProps对象时,TypeScript判定对象无法赋值给string类型,因此抛出类型不兼容错误。
以下是两种常见场景的解决方案:
场景1:底层组件仅接受string类型的icon参数
如果组件最终要把icon传给只接受字符串的底层组件,需要先从IconProps对象中提取icon字段的值:
interface IconProps { icon?: string; // Right icon // 其他实际属性 } type Props = { icon?: IconProps | string; // Right icon }; export function Icon({ icon = 'material-symbols:10k'}: Props) { // 区分处理string和IconProps类型的icon const iconValue = typeof icon === 'string' ? icon : icon?.icon; // 传递给底层图标组件 return <BaseIcon icon={iconValue} />; }
场景2:底层组件接受完整的IconProps对象
如果组件需要传递完整的IconProps对象,同时支持直接传入字符串作为icon字段的简写,可以将字符串参数转换为IconProps对象:
interface IconProps { icon?: string; // Right icon // 其他实际属性 } type Props = { icon?: IconProps | string; // Right icon }; export function Icon({ icon = 'material-symbols:10k'}: Props) { // 将string类型转换为IconProps对象,保持类型统一 const resolvedProps = typeof icon === 'string' ? { icon } : icon; // 展开传递给底层组件 return <BaseIcon {...resolvedProps} />; }
内容的提问来源于stack exchange,提问作者Komagain
相关产品推荐
相关产品推荐

