繁体   English   中英

Typescript & Gatsby: gatsby-plugin-ts + graphQL 查询集成

[英]Typescript & Gatsby: gatsby-plugin-ts + graphQL queries integration

我正在使用gatsby-plugin-ts为我的 graphql 页面查询生成类型。

我遇到的问题是生成的所有类型都返回T | undefined 所有字段的T | undefined类型,所以我需要在任何组件中使用它们之前检查所有查询子字段,否则编译器会抛出错误。

gatsby-plugin-image为例。 给定一个查询:

export const query = graphql`
  query IndexPage {
    banner: file(relativePath: { eq: "banner.jpg" }) {
      childImageSharp {
        gatsbyImageData(width: 1920)
      }
    }
  }
`;

结果data.banner应传递给getImage function,但如果您尝试这样做,typescript 可以理解地抛出以下错误,因为 undefined 不能分配给getImage预期的IGAtsbyImageData 打字稿错误

当涉及到更复杂的查询时,情况就更糟了,比如来自 markdownremark 插件的查询:每次都需要手动检查一个查询结果的所有子字段。 有解决办法吗?

data.banner 的类型应该是 ImageDataLike

export interface DataBannerProps {
  banner: ImageDataLike;
  alt: string;
}

这似乎是由gatsby-plugin-image中的错误引起的。 不幸的是getImagegetSrc等的类型与它们的 null-safe 行为不匹配 这看起来也只是部分修复,因为麻烦| null | null类型在{ childImageSharp: { gatsbyImageData: IGatsbyImageData } | null }上下降了一级 { childImageSharp: { gatsbyImageData: IGatsbyImageData } | null } (至少在 GraphQL Typegen 分型 - YMMV 中)。

最简单的解决方法是使用类型断言

const result = getImage(data.banner as ImageDataLike);

这告诉 Typescript:“嘿,我知道这些类型不完全匹配,但相信我data.banner将永远是ImageDataLike ”。


当然,如果您愿意手动定义您的类型,您可以避免所有这些,就像@Alexey 的回答一样。

如果你想坚持使用自动生成的类型,我建议升级到 Gatsby 内置并保持最新的官方GraphQL Typegen

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM