TypeScript Expo React Native中Styled Components自定义主题类型配置问题
问题排查与修复步骤
你当前的配置存在3个核心错误,按以下顺序修改即可生效:
1. 修正主题定义文件的类型标注
你在themes/index.ts中提前给theme变量绑定了原生DefaultTheme类型,导致TS自动推导的类型丢失了自定义属性。
修改themes/index.ts代码:
// 移除提前绑定的DefaultTheme类型,让TS自动推导主题实际结构 import { colors } from "./colors"; import { sizes } from "./sizes"; import { spacing, lineHeights } from "./spacing"; const theme = { colors, sizes, spacing, lineHeights, }; export default theme;
2. 修正类型声明文件配置
存在三个问题:导入主题的路径错误、扩展的模块与实际使用的styled-components/native不匹配、手动声明写法存在属性结构错误和笔误。
推荐使用自动继承类型的写法,修改types/theme.d.ts代码:
import type theme from "../src/themes"; // 修正路径,你的themes文件夹在src目录下 declare module "styled-components/native" { export interface DefaultTheme extends typeof theme {} }
如果你要用手动声明的写法,注意属性结构要和实际主题匹配,修正后代码:
declare module "styled-components/native" { export interface DefaultTheme { colors: { // bg属于colors下的属性,不要放到根节点 bg: { primary: string; secondary: string; } // 其余colors下的属性自行补充 }; sizes: string[]; // 修正笔误stringp -> string lineHeights: { title: string; copy: string; }; spacing: string[]; } }
3. 修正tsconfig配置
你当前的paths配置会导致所有全局导入都优先匹配types文件夹,影响正常模块解析,没有别名需求的话直接删除该配置即可:
{ "extends": "expo/tsconfig.base", "compilerOptions": { "strict": true, "baseUrl": "." }, "include": ["./src", "./types"], "exclude": [ "node_modules", "**/*.test.ts", "**/*.test.tsx" ] }
最后生效操作
修改完成后重启TS服务:
- VSCode用户按
Ctrl+Shift+P(Mac用户Cmd+Shift+P),选择「TypeScript: Restart TS Server」即可看到类型提示正常生效。
内容的提问来源于stack exchange,提问作者me-me
相关产品推荐
相关产品推荐

