如何在Next.js中为GraphQL查询添加TypeScript类型支持
给Next.js GraphQL查询添加TypeScript类型的最优方案
最省心且高效的方案是用GraphQL Code Generator自动生成类型,完全不用手动编写重复的类型定义,还能保证和GraphQL Schema严格一致,避免手动维护的出错风险。
步骤1:安装依赖
先安装代码生成工具及必要插件:
npm install --save-dev @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo # 用yarn的话 yarn add -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo
步骤2:配置代码生成器
在项目根目录创建codegen.ts配置文件:
import type { CodegenConfig } from '@graphql-codegen/cli'; const config: CodegenConfig = { // 替换成你的GraphQL Schema地址,比如公共的国家API:https://countries.trevorblades.com/ schema: 'https://your-graphql-api-endpoint.com', // 指定包含GraphQL查询的文件路径,比如pages下所有ts/tsx文件 documents: ['./pages/**/*.{ts,tsx}'], generates: { // 生成的类型文件输出路径 './src/generated/graphql.ts': { plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'], config: { skipTypename: false, withHooks: true, }, }, }, }; export default config;
步骤3:添加生成脚本
在package.json中添加脚本,方便快速生成/更新类型:
{ "scripts": { "codegen": "graphql-codegen --config codegen.ts", "codegen:watch": "graphql-codegen --config codegen.ts --watch" } }
步骤4:生成类型并修改业务代码
运行npm run codegen,工具会自动扫描项目中的GraphQL查询,生成对应的TypeScript类型。之后修改你的getStaticProps代码:
import { client } from '../path-to-your-apollo-client'; // 导入自动生成的类型和查询文档 import { CountriesQuery, CountriesDocument } from '../src/generated/graphql'; export async function getStaticProps() { // 用生成的类型标注查询返回值 const { data } = await client.query<CountriesQuery>({ query: CountriesDocument, }); return { props: { // 这里countries会自动获得正确的类型提示 countries: data.countries.slice(0, 4), }, }; }
备选:手动定义类型(仅适合简单场景)
如果不想引入代码生成工具,也可以手动编写类型,但需要自己维护,容易和Schema更新不同步:
// 手动定义数据类型 type Country = { code: string; name: string; emoji: string; }; type CountriesQueryData = { countries: Country[]; }; export async function getStaticProps() { const { data } = await client.query<CountriesQueryData>({ query: gql` query Countries { countries { code name emoji } } `, }); return { props: { countries: data.countries.slice(0, 4), }, }; }
显然自动生成方案更优,尤其是在查询较多的项目中,能大幅减少重复工作,确保类型准确性。
内容的提问来源于stack exchange,提问作者Alexis
相关产品推荐
相关产品推荐

