You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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的全局主题类型:

  1. 在项目中新建styled.d.ts类型声明文件,写入以下内容:
import 'styled-components';

declare module 'styled-components' {
  export interface DefaultTheme {
    // 按你实际的主题配置补充对应属性
  }
}
  1. 调整你的组件代码,将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 16:15:00