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

Gatsby+TS+GraphQL Typegen组件批量导入Fragment属性为Props的方法

便捷导入Gatsby GraphQL Fragment所有字段为组件Props的方法

直接利用Gatsby GraphQL Typegen生成的Fragment完整类型即可,无需逐个声明字段:

修改后的组件代码

import { graphql } from 'gatsby';

// 使用Partial让Fragment所有字段变为可选属性
const Footer = ({ id, name, phone }: Partial<Queries.FooterFragment>): JSX.Element => {
  return <footer>{phone}</footer>;
};
export default Footer

export const query = graphql`
  fragment Footer on ContentfulBlockFooter {
    id
    name
    phone
  }`;

说明

  • Gatsby的GraphQL Typegen会自动为你定义的Footer Fragment生成对应的完整类型Queries.FooterFragment,包含id、name、phone所有字段的类型信息。
  • 如果希望所有props字段都是必传的,去掉Partial<>即可:
    const Footer = ({ id, name, phone }: Queries.FooterFragment): JSX.Element => {
      return <footer>{phone}</footer>;
    };
    
  • 这样你可以直接解构出Fragment里的任意字段作为组件props,不用手动逐个声明每个字段的类型。

内容的提问来源于stack exchange,提问作者Sebastian Berg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:01:16