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

React+TypeScript中导入Styled Components JS文件遇类型声明错误

问题:TypeScript无法识别JS模块中的styled-components组件

我将React组件拆分为Index.tsx和Style.js两个文件,把样式放在Style.js中以简化Index.tsx,但从Style.js导入styled组件时出现TypeScript错误:

Could not find a declaration file for module './Style'. '/Users/sjoerdvermeijden/Sites/react-vite-typescript-todo/src/components/Footer/Style.js' implicitly has an 'any' type.

相关代码

  • Index.tsx中的导入语句:
import { FooterWrapper } from "./Style";
  • Style.js中的样式代码:
import styled from "styled-components";

export const FooterWrapper = styled.div`
  padding: 25px 0;
  background: var(--darkgray);
  color: white;
`;

已安装依赖

npm i -D @types/styled-components
npm i styled-components

解决方法

方法1:重命名样式文件为TypeScript后缀

直接将Style.js重命名为Style.ts或Style.tsx,TypeScript会自动识别文件中的类型,导入路径无需修改,即可消除错误。

方法2:手动添加类型声明文件

在Style.js所在目录下创建Style.d.ts文件,写入以下类型声明:

import styled from "styled-components";

export const FooterWrapper: ReturnType<typeof styled.div>;

该声明会告诉TypeScript FooterWrapper是styled-components生成的div组件类型。

方法3:配置tsconfig.json允许处理JS文件

修改项目根目录下的tsconfig.json,添加或调整以下编译选项:

{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": true
  }
}
  • allowJs: 允许TypeScript编译和处理JavaScript文件
  • checkJs: 开启对JavaScript文件的类型检查,让TypeScript自动识别styled-components导出组件的类型

内容的提问来源于stack exchange,提问作者Sjoerd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 00:31:13