TypeScript无法识别类型,报错Property 'width' does not exist怎么解决
报错原因
你传入styled泛型的BoxProps仅定义了width属性,没有包含theme的类型定义,TypeScript 推导时误将你传入的泛型整体绑定为theme的类型,导致识别不到顶层的width属性。
解决方案
快速修复
直接在解构参数处补充类型声明,告知 TypeScript 顶层参数包含width属性:
type BoxProps = { width: string; } const Box = styled('div')<BoxProps>(({ theme, width }: { theme: any; width?: string }) => ({ width: width || '100%' }));
规范类型写法
如果要做完整的类型校验,先扩展styled-components的全局主题类型:
- 在项目中新建
styled.d.ts类型声明文件,写入以下内容:
import 'styled-components'; declare module 'styled-components' { export interface DefaultTheme { // 按你实际的主题配置补充对应属性 } }
- 调整你的组件代码,将
theme类型纳入自定义props的定义:
import { DefaultTheme } from 'styled-components'; type BoxProps = { width?: string; theme: DefaultTheme; } const Box = styled('div')<BoxProps>(({ width }) => ({ width: width || '100%' }));
内容的提问来源于stack exchange,提问作者bp123
相关产品推荐
相关产品推荐

