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

如何为自定义Styled-Components声明custom.d.ts以解决TS属性报错?

解决React Native中Styled-Components自定义属性的TypeScript报错

步骤1:创建类型声明文件

在项目的src/types目录下创建custom.d.ts(若目录不存在则新建),确保TypeScript能扫描到该文件(可通过tsconfig.json的include配置指定)。

步骤2:编写类型扩展代码

在custom.d.ts中添加以下代码,扩展styled-components/native的类型系统,声明你的自定义属性:

import 'styled-components/native';
import { TouchableOpacityProps, TextProps } from 'react-native';

// 定义GlobalButton的自定义属性
interface GlobalButtonCustomProps {
  bc?: string;    // 背景色
  width?: number; // 宽度
  height?: number;// 高度
}

// 定义GlobalText的自定义属性
interface GlobalTextCustomProps {
  color?: string;   // 文字颜色
  fontSize?: number;// 字体大小
  fw?: number;      // 字体粗细
}

// 扩展styled-components的原生组件类型
declare module 'styled-components/native' {
  export interface StyledTouchableOpacityProps
    extends TouchableOpacityProps,
      GlobalButtonCustomProps {}

  export interface StyledTextProps extends TextProps, GlobalTextCustomProps {}
}

步骤3:配置tsconfig.json(可选)

如果TypeScript未自动识别到类型文件,在tsconfig.json中添加以下配置:

{
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types", "./src/types"]
  },
  "include": ["src/**/*", "src/types/**/*"]
}

原理说明

TypeScript默认无法识别你给styled-components组件添加的自定义属性,通过扩展styled-components/native模块的类型接口,我们可以告诉TypeScript这些属性是合法的,从而消除报错。

内容的提问来源于stack exchange,提问作者Gilmar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:45:19