NextJS集成Twin.Macro+Styled Components+TS出现Interpolation类型报错
报错原因
styled-components 默认未关联 twin.macro 自动生成的 Tailwind 主题类型,导致 theme 工具函数返回的插值类型与 styled-components 预期的 Interpolation<ThemeProps> 类型不匹配,ThemeProps 被 TypeScript 推断为 never 类型,触发类型校验错误。
解决方案
- 第一步:在项目根目录(或 src 目录下)新建
styled-components.d.ts类型声明文件,写入以下内容扩展 styled-components 的默认主题类型:
import 'styled-components' import type { TwinTheme } from 'twin.macro' declare module 'styled-components' { export interface DefaultTheme extends TwinTheme {} }
如果导入 TwinTheme 出现类型报错,可替换为导入 Theme 类型再继承即可。
- 第二步:检查项目
tsconfig.json的include配置,确保包含了上述声明文件,示例配置如下:
{ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.d.ts"] }
- 完成配置后重启 TypeScript 语言服务即可消除错误(VS Code 可通过快捷键
Ctrl+Shift+P选择「TypeScript: Restart TS Server」重启)。
内容的提问来源于stack exchange,提问作者antonwilhelm
相关产品推荐
相关产品推荐

