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

Gatsby迁移TypeScript时GatsbyImageData与Mdx相关类型缺失问题求助

Gatsby + TypeScript重构:MDX查询与ImageSharp类型定义指引

刚接触TypeScript就重构Gatsby站点确实会遇到类型定义的小坑,我来帮你梳理这两个缺失的类型:

1. childImageSharp.fixed 的正确类型

你提到旧版gatsby-image的FixedObject已经不再适用,这是因为gatsby-plugin-image使用了全新的类型体系。对于fixed格式的图片数据,你需要从gatsby-plugin-image导入FixedImageData类型:

import { FixedImageData, IGatsbyImageData } from "gatsby-plugin-image";

然后把fixed: any替换为:

fixed: FixedImageData;

注意:如果你的查询是基于gatsby-transformer-sharp的传统fixed字段(而非新的gatsbyImageData),这个类型完全匹配返回的结构,包含宽度、高度、src、srcSet等所有固定尺寸图片的属性。

2. MdxQuery.body 的正确类型

MDX查询返回的body是编译后的可渲染JSX字符串,你可以直接将其类型定义为string——这是最直接且兼容<MDXRenderer>组件的方式。不过如果你想要更精准的类型,可以从gatsby-plugin-mdx导入官方提供的类型:

首先导入类型:

import { Mdx } from "gatsby-plugin-mdx";

然后你可以直接复用Mdx类型中的body定义,或者调整你的MdxQuery类型:

type MdxQuery = Pick<Mdx, "id" | "body" | "excerpt"> & {
  frontmatter: Frontmatter;
};

如果不想依赖官方类型,直接定义body: string也完全够用,因为<MDXRenderer>接收字符串类型的编译后内容。

修改后的完整类型示例

import { FixedImageData, IGatsbyImageData } from "gatsby-plugin-image";
import { Mdx } from "gatsby-plugin-mdx";

type Frontmatter = {
  title: string;
  titlestrap: string | null;
  category: string;
  slug: string;
  metaDescription: string | null;
  author?: string | null;
  featuredImage: {
    childImageSharp: {
      fixed: FixedImageData; // 替换any为FixedImageData
      gatsbyImageData: IGatsbyImageData;
    };
  };
};

type MdxQuery = Pick<Mdx, "id" | "body" | "excerpt"> & {
  frontmatter: Frontmatter;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 15:47:39