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

Next.js 14中SVG导入被TypeScript推断为any的问题及解决方法

解决Next.js 14中SVG导入类型为any的ESLint报错问题

以下两种方法可以在不修改TS配置规则的前提下解决你的问题:

方法一:添加SVG类型声明文件

在项目根目录或者app/assets文件夹下创建一个名为svg.d.ts的类型声明文件,写入以下内容:

import type { StaticImageData } from 'next/image';

declare module '*.svg' {
  const content: StaticImageData;
  export default content;
}

这个文件会告诉TypeScript,所有.svg后缀的模块默认导出类型为StaticImageData,这样你导入SVG时类型就会被正确推断,无需修改现有导入代码。

方法二:导入SVG时使用类型断言

如果不想新增类型声明文件,可以在导入SVG时直接用类型断言将其转换为StaticImageData:

import image1 from './image1.jpg';
import image2 from './image2.jpg';
import image3 from './image3.svg' as unknown as StaticImageData;

export const images: {[key : string] : StaticImageData} = {image1, image2, image3};

这里用as unknown as StaticImageData是因为直接断言可能会触发TS的类型检查警告,先转成unknown再转目标类型是更安全的写法。

两种方法都能让ESLint不再提示不安全的any类型赋值,你可以根据自己的项目习惯选择其中一种。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 09:42:43