提问人:workK 提问时间:4/28/2023 最后编辑:workK 更新时间:4/30/2023 访问量:607
NextJs:从公用文件夹导入的图像的类型声明
NextJs: Type declaration for images imported from public folder
问:
我可以知道从nextjs中的公共文件夹导入的图像的类型声明是什么吗?
我在utils文件夹中创建了一个名为data的文件。在数据文件中,我从公共文件夹导入了图像,并使用 tile、desc、image 等键创建了一个对象数组。
例如const users = [ { avatar: img1, name: "some name", age: 12, }, { avatar: img2, name: "some name", age: 14, } ]
当我为用户 obj 提供类型时,它显示错误Types of property 'img' are incompatible. Type 'StaticImageData' is missing the following properties from type 'HTMLImageElement': align, alt, border, complete, and 306 more.ts(2322)
有人可以告诉我从公共文件夹导入并在对象数组中使用它的图像的确切类型吗
我试图更改 staticimagetype,但找不到
// data.ts file
export const SuccessStoriesCardData= [
{
title: "Some title",
content: "some content",
img:img1
},
{
title: "Some title",
content: "some content",
img:img2
},
{
title: "Some title",
content: "some content",
img:img3
},
]
img1、img2、img3 是从公用文件夹导入的
类型
export type DataType = {
img: HTMLImageElement;
title: string;
desc: string;
}
当我将此类型提供给子组件并导入父组件中的数据并传递给子组件时,上述类型错误即将到来
答:
从公用文件夹导入映像时,编译器会将这些映像分析为具有该映像的所有必要详细信息的类型对象。它们不会作为组件或 HTML 元素导入。这就是为什么当您尝试将它们分配给类型为 的属性时,typescript 会给出类型不匹配错误。您可以通过使用导入的图像数据作为组件的 src 来避免这种情况:StaticImageData
avatar
HTMLImageElement
Image
import Image from 'next/image'
import UserImage from '../public/images/user.jpeg'
interface User {
image: StaticImageData;
name: string;
}
const users: User[] = [
{
image: UserImage
name: "John"
},
{
image: UserImage
name: "Alen"
}
]
export default function Users() {
return (
<div>
{
users.map((user, i) => (
<div key={i}>
<Image src={user.image} alt={user.name} width={100} height={100}/>
<h3>{user.name}</h3>
</div>
))
}
</div>
)
}
您可以在此处了解有关 Next.js 静态文件服务的更多信息,并在此处了解有关下一张图像的更多信息。
这是因为 nextjs 中导入的大多数图像都有 type .
大多数图像: .StaticImageData
*.png, *.jpg, *.jpeg, *.gif, *.webp, *.avif, *.ico, *.bmp
在 Github 中查看源代码
// this file is conditionally added/removed to next-env.d.ts // if the static image import handling is enabled declare module '*.png' { const content: import('../dist/client/image').StaticImageData export default content } ...
Typescript 试图告诉您正确的类型是 。StaticImageData
应将 type of 更新为 。img
StaticImageData
export type DataType = {
img: StaticImageData; /* Use StaticImageData instead of HTMLImageElement */
title: string;
desc: string;
}
评论