TypeScript中使用styled component传自定义props出现隐式any报错如何解决
问题原因
该报错是 TypeScript 严格模式下noImplicitAny规则生效的表现:要求所有函数参数必须有明确的类型定义,你设置strict: false属于关闭全局类型校验绕开问题,会丢失大量类型安全能力,不推荐使用。
正确解决方案
- 第一步先确认依赖安装正确
如果你使用的是 styled-components v5 及更早版本,需要先安装官方类型声明包:
如果你使用的是 styled-components v6 及以上版本,类型已经内置无需额外安装。npm install @types/styled-components -D # 或pnpm pnpm add @types/styled-components -D # 或yarn yarn add @types/styled-components -D - 第二步给模板字符串内的函数参数显式标注类型
你已经定义了TagProps接口,只需要给箭头函数的props参数绑定该类型即可,两种常用写法:- 直接标注props类型
interface TagProps { fontSize?: string } const Ptag = styled.p<TagProps>` font-size: ${(props: TagProps) => props.fontSize ? props.fontSize : "12px"}; `- 解构props时标注(更推荐,可读性更高)
这里使用空值合并运算符interface TagProps { fontSize?: string } const Ptag = styled.p<TagProps>` font-size: ${({ fontSize }: TagProps) => fontSize ?? "12px"}; `??代替三元判断写法更简洁。
完成以上操作后不需要关闭strict模式,报错就会消失,同时保留完整的类型校验能力。
内容的提问来源于stack exchange,提问作者user3066610
相关产品推荐
相关产品推荐

