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

Typescript如何将Array<A>|Array<B>转为Array<A|B>并正确转换Schema类型

解决方案

修复ConvertSchema泛型工具类型

你遇到的推导异常是TypeScript分布式条件类型的默认特性导致的:当裸类型参数为联合类型时,会自动拆分到每个联合分支单独执行类型逻辑,再把结果联合。你只需要阻止这个分发行为即可,修改后的工具类型如下:

// 先定义阻止分发的ValueOrArray工具类型
type ValueOrArray<T> = [T] extends [unknown] ? T | T[] : never

type ConvertSchema<T> = {
  [key in keyof T]?: ValueOrArray<T[key]>
}

应用到你的Schema类型上后,得到的推导结果完全符合预期:

type ConvertedSchema = ConvertSchema<Schema>
// 推导结果为:
// {
//   name?: string | string[] | undefined;
//   status?: "Active" | "Blocked" | ("Active" | "Blocked")[] | undefined;
// }

实现Array<A> | Array<B>到Array<A | B>的转换

可以通过infer提取数组元素的联合类型,再组装成新数组即可,工具类型实现如下:

type UnionArrayToUnionArr<T> = T extends Array<infer Elem> ? Elem[] : never

// 用法示例
type StatusArr = "Active"[] | "Blocked"[]
type ConvertedArr = UnionArrayToUnionArr<StatusArr>
// 推导结果为:("Active" | "Blocked")[]

内容的提问来源于stack exchange,提问作者Saif Ali Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:27:04