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

TypeGraphQL是否支持嵌套联合类型?如何合并已有联合类型?

解决TypeGraphQL嵌套联合类型的问题

你遇到的问题是因为createUnionType返回的是一个联合类型的元数据对象,而非类本身——TypeGraphQL要求联合类型的types参数必须是类构造函数的数组,不能直接传入已有的联合类型实例。不过要实现你想要的InstagramWidget1 | InstagramWidget2 | SpotifyWidget1 | SpotifyWidget2这个联合类型,有两种简单可行的方案:

方案1:直接罗列所有底层类

最直接的方式就是把所有需要的Widget类直接放进新联合类型的types数组里:

const WidgetUnion = createUnionType({
  name: "Widget",
  types: () => [InstagramWidget1, InstagramWidget2, SpotifyWidget1, SpotifyWidget2] as const,
});

这种方式代码简洁直观,适合底层类数量不多的场景。

方案2:复用已有联合类型的成员定义

如果你想复用之前InstagramUnion和SpotifyUnion的成员定义,可以先把它们的类数组抽成独立变量,再合并使用:

// 先抽离每个联合类型的成员类数组
const instagramWidgetClasses = [InstagramWidget1, InstagramWidget2] as const;
const spotifyWidgetClasses = [SpotifyWidget1, SpotifyWidget2] as const;

// 重新创建原来的联合类型
const InstagramUnion = createUnionType({
  name: "Instagram",
  types: () => instagramWidgetClasses,
});

const SpotifyUnion = createUnionType({
  name: "Spotify",
  types: () => spotifyWidgetClasses,
});

// 合并数组创建顶层联合类型
const WidgetUnion = createUnionType({
  name: "Widget",
  types: () => [...instagramWidgetClasses, ...spotifyWidgetClasses] as const,
});

这样既保留了原有联合类型的复用性,又能正确生成包含所有Widget类的顶层联合类型。

为什么原来的写法会报错?

TypeGraphQL的createUnionType函数返回的是一个用于描述联合类型的内部元数据对象,它并不是一个可以被其他联合类型引用的类类型。所以当你把SpotifyUnion和InstagramUnion放进types数组时,TypeScript会检测到类型不匹配——因为数组期望的是类构造函数,而你传入的是联合类型元数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:45:36