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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 05:00:00