Next.js+TypeScript中styled-components类型错误求助
解决Next.js + TypeScript中styled-components的类型错误
问题复现
使用Next.js + TypeStack开发,安装了styled-components v6.1.13,编写Card.styled.ts后出现两个TypeScript错误:
- Unsafe assignment of an error typed value
- Unsafe use of a(n) 'error' type typed template tag
已尝试安装@types/styled-components,问题未解决。
解决方案
1. 卸载多余的@types/styled-components
styled-components v6及以上版本自带官方类型定义,第三方@types/styled-components会和内置类型冲突,执行卸载命令:
npm uninstall @types/styled-components # 或使用yarn yarn remove @types/styled-components
2. 配置Next.js的SWC编译器
Next.js 13+默认使用SWC,需要启用styled-components的SWC插件以确保类型兼容,修改next.config.js:
/** @type {import('next').NextConfig} */ const nextConfig = { compiler: { styledComponents: true, }, }; module.exports = nextConfig;
3. 调整CSS语法(可选)
你使用的rgb(255 255 255 / 0.1)是CSS Color Module Level 4的空格分隔语法,目前styled-components的类型定义对该语法的支持可能不完善。可以改为传统逗号分隔的rgba写法:
import styled from "styled-components"; export const StyledCard = styled.div` max-width: 20rem; display: flex; flex-direction: column; gap: 1rem; padding: 1rem; border-radius: 0.75rem; color: white; background-color: rgba(255, 255, 255, 0.1); `;
4. 检查TypeScript配置
确保tsconfig.json包含必要的编译选项:
{ "compilerOptions": { "jsx": "preserve", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, "esModuleInterop": true, "target": "ESNext", "lib": ["DOM", "DOM.Iterable", "ESNext"] } }
5. 重启开发环境
完成以上操作后,重启Next.js开发服务器和IDE的TypeScript语言服务,错误通常会消失。
内容的提问来源于stack exchange,提问作者Itay Tur
相关产品推荐
相关产品推荐

