在 next.js 13 中设置 og 图像:打字稿错误:'string | undefined' 不能分配给类型 'OGImage'

问题描述 投票:0回答:1

我正在开发一个动态页面,并尝试按照docs生成元数据。我在设置 og 图像时遇到问题

export async function generateMetadata(
  { params }: Props,
  parent: ResolvingMetadata
): Promise<Metadata> {
  const { data } = await getAllArts();
  const slug = params.slug;
  const product = data.find((item: ArtProduct) => item.slug === slug);

  return {
    title: product ? product.title : ".....",
    openGraph: {
      images: [product?.coverImage ] ,
    },
  };
}

封面图片托管在cloudinary 上。我收到打字稿错误:

Type 'string | undefined' is not assignable to type 'OGImage'.
  Type 'undefined' is not assignable to type 'OGImage'

我不知道

OGImage
类型是什么。我尝试导入它,但看起来它没有从 next.js 导出。

typescript next.js seo facebook-opengraph next.js13
1个回答
0
投票

问题是您的产品可能未定义,这会导致图像数组中设置未定义。

您可以检查产品对象,然后不设置值,或者更改为

images: [product?.coverImage || '' ] ,

如果产品不存在,最终设置备用图像的路径。

© www.soinside.com 2019 - 2024. All rights reserved.