如何导出包含Styled Components内置属性和自定义属性的扩展接口
报错原因
你自定义的CustomTypographyProps接口未包含Styled Components内置的多态属性(如as)的类型定义,所以TypeScript无法识别attrs回调中props上的as字段。
解决方案1:扩展原有自定义属性接口(推荐)
直接在你定义的Props接口中加入as属性的类型,一劳永逸解决所有使用该组件时的as属性类型识别问题:
import type { ElementType } from "react"; interface CustomTypographyProps { $typography?: 'display' | 'legible'; $size?: 'mega' | 'mini'; // 加入Styled Components内置多态属性的类型定义 as?: ElementType; // 如果需要用到forwardedAs属性也可以一起加 forwardedAs?: ElementType; }
解决方案2:在attrs回调中临时扩展props类型
如果你不想改动原有接口,可以直接在使用attrs的地方临时扩展props的类型:
import type { ElementType } from "react"; const LegibleTypography = styled(CustomTypography).attrs((props: CustomTypographyProps & { as?: ElementType }) => { return { $typography: 'legible', $size: props.as === 'h1' ? 'mega' : undefined } })``;
两种方案都可以解决类型报错,如果你后续多处会用到该组件的as属性,推荐用第一种方案统一处理类型。
内容的提问来源于stack exchange,提问作者Sophusk
相关产品推荐
相关产品推荐

