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

如何在TypeScript中提取嵌套枚举的数值类型?

从SystemState中提取枚举数值类型的方法

先看你提供的代码:

enum Stage {
  STARTED = 1,
  COMPLETED
}

const SystemState = {
  Stage,
}

你需要从SystemState中提取Stage枚举的数值类型(即1 | 2),而不是用keyof typeof SystemState['Stage']得到的字符串键名联合类型。

可以通过索引访问枚举类型的所有键对应值来实现:

type StageType = typeof SystemState['Stage'][keyof typeof SystemState['Stage']];
// 此时 StageType 的类型为 1 | 2

原理很直接:

  • typeof SystemState['Stage'] 获取到Stage枚举的类型
  • keyof typeof SystemState['Stage'] 拿到枚举的键名集合 "STARTED" | "COMPLETED"
  • 通过[keyof ...]的索引方式,取出每个键对应的数值,最终合并成数值联合类型

如果想让代码更清晰,也可以拆分两步:

// 先拿到枚举的类型
type StageEnum = typeof SystemState['Stage'];
// 再提取数值类型
type StageType = StageEnum[keyof StageEnum];

结果同样是1 | 2,满足你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 01:49:50