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

如何使用.d.ts文件为Styled Component添加类型定义?

给React Native项目中Styled Components添加.d.ts类型声明

在baseCSS.d.ts文件中,你可以按以下方式为Box组件添加类型:

1. 基础类型声明写法

首先导入需要的类型,定义自定义Props,然后通过declare module关联到你的baseCSS.js文件:

import type { ThemedStyledFunction } from 'styled-components/native';
import type { View } from 'react-native';

// 定义Box组件的自定义属性类型,和你之前JSDoc中使用的BoxProps一致
type BoxProps = {
  // 替换为你实际的属性定义,例如:
  padding?: number;
  backgroundColor?: string;
};

// 声明对应baseCSS.js的模块,让TypeScript将类型绑定到该JS文件的导出项
declare module './baseCSS' {
  export const Box: ThemedStyledFunction<typeof View, BoxProps>;
}

2. 带自定义主题的扩展写法

如果你的项目使用了自定义主题,只需补充ThemedStyledFunction的第三个泛型参数(主题类型):

import type { ThemedStyledFunction } from 'styled-components/native';
import type { View } from 'react-native';
import type { AppTheme } from './your-theme-path'; // 导入你的主题类型

type BoxProps = {
  padding?: number;
  backgroundColor?: string;
};

declare module './baseCSS' {
  export const Box: ThemedStyledFunction<typeof View, BoxProps, AppTheme>;
}

关键说明

  • 使用declare module是因为我们要给纯JavaScript文件添加类型声明,TypeScript需要通过模块路径关联类型与JS文件中的导出变量。
  • ThemedStyledFunction的三个泛型参数分别对应:基础组件类型(这里是React Native的View)、组件自定义Props类型、可选的主题类型,完全匹配你之前用JSDoc标注的类型逻辑。

内容的提问来源于stack exchange,提问作者Thiago Lino Gomes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:10:26