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

如何在TypeScript泛型中限制类型为单一指定联合类型?

解决TypeScript泛型限制为单一联合类型的问题

原来的代码中,<T extends ABType | TrueFalseType>的约束允许T是两个联合类型的任意子联合(比如"A" | "false"),因此混合元素的数组也能通过编译。要实现T只能完全属于ABType或TrueFalseType其中一个,有两种常用方案:

方案一:函数重载

通过定义多个重载签名,限定函数只能接受纯ABType数组或纯TrueFalseType数组:

type TrueFalseType = "true" | "false"
type ABType = "A" | "B"

// 重载签名,限定输入类型
function myFunction(values: Array<ABType>): void;
function myFunction(values: Array<TrueFalseType>): void;
// 实现签名,兼容两种类型
function myFunction(values: Array<ABType | TrueFalseType>) {
  console.log(values)
}

myFunction(["A", "B"]) // 正常通过
myFunction(["true", "false"]) // 正常通过
myFunction(["A", "false"]) // 触发编译错误

这种方式逻辑直观,代码可读性高,适合简单的多类型限定场景。

方案二:泛型约束结合条件类型

通过条件类型验证T是否完全属于其中一个联合类型,不符合则返回never触发错误:

type TrueFalseType = "true" | "false"
type ABType = "A" | "B"

// 自定义约束类型:确保T完全是U或V其中一个
type SingleUnionConstraint<T, U, V> = 
  T extends U ? (Exclude<T, U> extends never ? T : never) : 
  T extends V ? (Exclude<T, V> extends never ? T : never) : 
  never;

const myFunction = <T extends SingleUnionConstraint<T, ABType, TrueFalseType>>(values: Array<T>) => {
  console.log(values)
}

myFunction(["A", "B"]) // 正常通过
myFunction(["true", "false"]) // 正常通过
myFunction(["A", "false"]) // 触发编译错误

这里的SingleUnionConstraint会检查T是否没有超出U或V的范围,若T是混合的子联合(比如"A" | "false"),则会返回never,导致泛型约束不满足,触发编译错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 11:56:28