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

Next.js中如何为public文件夹导入的图片声明TypeScript类型?

Next.js中public文件夹导入图片的类型声明解决方案

你遇到的类型不匹配错误,是因为把图片类型声明为HTMLImageElement,但从public文件夹导入的图片实际是Next.js内置的StaticImageData类型,两者属性完全不同,导致类型校验失败。

解决步骤:

  1. 导入StaticImageData类型
    从next/image模块中导入这个内置类型,无需额外安装依赖:
import { StaticImageData } from 'next/image';
  1. 修正类型声明
    将DataType中的img字段类型替换为StaticImageData,同时注意字段名要和数据中的一致(你的数据里是content,类型里原来写的是desc,需要统一):
export type DataType = {
  img: StaticImageData;
  title: string;
  content: string;
};
  1. 为数据数组指定类型
    给SuccessStoriesCardData加上DataType[]类型约束,确保数组中每个对象都符合类型要求:
export const SuccessStoriesCardData: DataType[] = [
  {
    title: "Some title",
    content: "some content",
    img: img1
  },
  {
    title: "Some title",
    content: "some content",
    img: img2
  },
  {
    title: "Some title",
    content: "some content",
    img: img3
  }
];

补充说明:

  • HTMLImageElement是浏览器DOM中<img>元素的类型,代表页面上的图片DOM节点;而你导入的本地静态图片资源,对应的是Next.js处理后返回的StaticImageData,它包含图片的路径、宽高、模糊占位图等静态资源信息。
  • 若在子组件中使用next/image组件渲染图片,直接传递img字段即可,因为next/image的src属性原生支持StaticImageData类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 17:02:44