【问题标题】:TypeScript error tells me "Property 'fluid' does not exist on type 'GatsbyImage'"TypeScript 错误告诉我“'GatsbyImage' 类型上不存在属性 'fluid'”
【发布时间】:2021-03-01 06:02:10
【问题描述】:

在 Gatsby 中,我使用了页面查询来检索一些数据:

allContentfulArtwork(sort: { fields: [artistName], order: ASC }) {
  edges {
    node {
      image {
        fluid(resizingBehavior: SCALE) {
          ...GatsbyContentfulFluid
        }
      }
      altTag
      title
      artistName
      countryOfOrigin
      contentful_id
    }
  }
}

我将此查询的结果保存在一个名为artworkData 的变量中。我有一个 React 组件,它在 props 中接受此数据以将其呈现到页面(与此问题无关的 props 用 * 标记,可以忽略):

{artworkData.edges.map((artwork) => {
  return (
    <Artwork
      *alreadyVoted={alreadyVoted}
      altTag={artwork.node.altTag}
      artistName={artwork.node.artistName}
      contentful_id={artwork.node.contentful_id}
      countryOfOrigin={artwork.node.countryOfOrigin}
      *hasVoted={hasVoted}
      image={artwork.node.image}
      key={artwork.node.contentful_id}
      *location={location}
      title={artwork.node.title}
      ></Artwork>
  );
})}

我在下面的 TypeScript 界面中定义了Artwork 组件的 props 的形状:

interface ArtworkProps {
  alreadyVoted(): void;
  altTag: string;
  artistName: string;
  contentful_id: string;
  countryOfOrigin: string;
  hasVoted: boolean;
  image: GatsbyImage;
  location: GatsbyRouteComponentProps;
  title: string;
}

我解构了我的道具并在组件中使用它们(为简洁起见,省略了样式化的组件定义):

const Artwork: React.FC<ArtworkProps> = ({ alreadyVoted, altTag, artistName, contentful_id, countryOfOrigin, hasVoted, image, location, title }) => {
  return (
    <ArtworkWrapper>
      <Img fluid={image.fluid} alt={altTag ? altTag : title}></Img>
    < /ArtworkWrapper>

    // a bunch of additional render code
  )
}

不幸的是,TypeScript 说"Property 'fluid' does not exist on type 'GatsbyImage'.ts(2339)"

嗯,我认为确实如此,因为 Gatsby 中的 Img 组件具有 fluid 属性,您可以使用该属性传递流体数据以进行渲染。据我通过the index.d.ts file in Gatsby Image 看到的,这个属性确实存在。如果我们按照层次结构,GatsbyImage 类包含GatsbyImageProps 类型,可以是GatsbyImageFluidProps 接口或GatsbyImageFixedProps 接口; GatsbyImageFluidProps 定义了流体属性。

我正在使用 gatsby 2.26.1、gatsby-image 2.5.0、TypeScript 4.0.5。 VSCode 1.51.1 中显示警告。

【问题讨论】:

  • 查询的其余部分是否正确获取数据?
  • @FerranBuireu 确实,所有数据都正确输入。我可以看到图像本身,只是打字问题。

标签: javascript reactjs typescript gatsby gatsby-image


【解决方案1】:

您似乎要导入 GatsbyImage 类,其传入属性为 GatsbyImageProps 并且 GatsbyImage 类不会导出除自身以外的任何内容。

您想导入 GatsbyImageProps https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-image/index.d.ts#L65 并将其分配给您的 Artwork 组件的 props 类型。

【讨论】:

  • 那你是不是建议我把我界面中image的类型改成GatsbyImageProps?我试过这个,不幸的是它没有任何区别。事实上,错误仍然是一样的 - Property 'fluid' does not exist on type 'GatsbyImage'。因此,我认为 TS 以某种方式以其推论覆盖了我的声明?如果我明确说明它是GatsbyImageProps 类型,它怎么能继续给我与GatsbyImage 相关的错误?
猜你喜欢
  • 2019-08-17
  • 2023-02-21
  • 2019-04-12
  • 2020-07-09
  • 2019-10-20
  • 2021-09-26
  • 2021-09-06
  • 2016-09-07
  • 2020-03-25
相关资源
最近更新 更多