简体   繁体   中英

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

I'm using gatsby-plugin-ts to generate types for my graphql page queries.

The issue I have is that all types generated return a T | undefined T | undefined type for all fields, so I would need to check all query subfields before using them in any component, otherwise the compiler will throw an error.

Take gatsby-plugin-image for example. Given a query:

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

The result data.banner should be passed to the getImage function, though if you try to do so typescript understandably throws the following error, since undefined is not assignable to IGAtsbyImageData expected by getImage 打字稿错误

And this is even worse when it comes to more complex queries, like the ones from the markdownremark plugin: all subfields of one query result would need to be manually checked every time. Is there a work around for this?

type of data.banner should be ImageDataLike

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

This appears to be caused by a bug in the gatsby-plugin-image typings. Unfortunately the typings for getImage , getSrc , etc. don't match their null-safe behaviour . This also looks like it was only partially fixed, since the troublesome | null | null type is down one level on { childImageSharp: { gatsbyImageData: IGatsbyImageData } | null } { childImageSharp: { gatsbyImageData: IGatsbyImageData } | null } (at least in the GraphQL Typegen typings - YMMV).

The easiest workaround is to use a type assertion :

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

This tells Typescript: "Hey, I know these types don't exactly match, but trust me , data.banner will always be an ImageDataLike ".


Of course, you can avoid all this if you're happy to define your typings manually, as in @Alexey's answer.

If you want to stick with auto-generated types, I'd recommend upgrading to the official GraphQL Typegen which is built into Gatsby and kept up-to-date.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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