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

如何创建仅接受单一枚举值集合的TypeScript类型?

实现仅包含单一枚举所有值的类型安全数组

现有两个const枚举定义如下:

const enum Color {
  red = 'red',
  blue = 'blue',
}

const enum Shape {
  rectangle = 'rectangle',
  square = 'square',
  circle = 'circle'
}

需求是创建一种类型,让数组仅接受第一个枚举的所有值,或第二个枚举的所有值,具体要求:

  • 数组元素必须全部来自同一个枚举
  • 数组不能为空
  • 不能包含枚举外的其他值

之前的错误尝试

直接将两个枚举的字符串值联合成类型再定义数组的写法无法满足需求,因为它允许数组混入不同枚举的值:

type Characteristics = `${Color}` | `${Shape}`

const characteristic: Characteristics[] = ['circle', 'red']; // 未报错,但实际不符合需求

解决方案

可以通过定义非空的单一枚举元素数组类型来实现:

// 定义非空的单一类型数组
type FullEnumArray<T extends string> = [T, ...T[]];

// 组合成目标类型:要么是非空Color数组,要么是非空Shape数组
type Characteristics = FullEnumArray<`${Color}`> | FullEnumArray<`${Shape}`>;

验证案例

以下是符合需求的类型校验结果:

const char1: Characteristics = ['circle', 'square']; // ✅ 合法:所有元素均为Shape枚举值
const char2: Characteristics = ['circle', 'red']; // ❌ 报错:混入了Shape和Color的枚举值
const char3: Characteristics = []; // ❌ 报错:空数组不符合非空要求
const char4: Characteristics = ['test', 'red', 'blue']; // ❌ 报错:包含枚举外的非法值

说明

  • FullEnumArray<T> 确保数组至少有一个元素,且所有元素类型统一为T
  • ${Color} 和 ${Shape} 是TypeScript的字符串字面量类型推导,能正确获取const枚举的字符串值联合类型
  • 联合类型FullEnumArray<...> | FullEnumArray<...> 强制数组只能属于其中一种枚举的非空集合

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 20:56:07