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

如何缩小并复用GraphQL Codegen自动生成的TS类型?处理组件Props类型问题

解决GraphQL Codegen生成可选数组类型的组件Props标注问题

你可以通过以下几种方式正确标注单个thread的类型,避开threads可选性带来的类型问题:

1. 直接用NonNullable提取数组元素类型

利用TypeScript的NonNullable工具类型剔除threads的null和undefined类型,再获取数组元素类型:

type Thread = NonNullable<AnnotationsQuery["threads"]>[number];

之后组件Props就可以直接用这个Thread类型:

interface ThreadComponentProps {
  thread: Thread;
}

2. 复用GraphQL Codegen自动生成的嵌套类型

GraphQL Codegen默认会为查询中的所有嵌套对象生成独立的类型定义。你可以直接查看生成的类型文件,通常能找到单独的Thread类型(和查询里的__typename对应),直接导入使用即可:

import { Thread } from './generated/graphql';

interface ThreadComponentProps {
  thread: Thread;
}

3. 自定义通用工具类型提取数组元素

如果需要处理更多类似场景,可以定义一个通用工具类型来提取数组元素:

type ExtractArrayElement<T> = T extends Array<infer U> ? U : never;
type Thread = ExtractArrayElement<NonNullable<AnnotationsQuery["threads"]>>;

另外注意,在遍历threads时一定要先做空值判断,既保证类型安全也避免运行时错误:

// 确保threads存在后再遍历
if (data?.threads) {
  data.threads.map(thread => <ThreadComponent thread={thread} />);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:27:06