如何在 TypeScript 中创建嵌套枚举的类型?

问题描述 投票:0回答:1
enum Stage {
  STARTED = 1,
  COMPLETED
}

const SystemState = {
  Stage,
}

是否可以通过从

SystemState
对象中提取枚举来创建类型,即

type stageType -> 1 | 2 (corresponds to the integral values of the Stage enum)

我尝试过

keyof typeof SystemState['Stage']
,但这会创建一个字符串联合类型:
"STARTED" | "COMPLETED"

javascript typescript enums
1个回答
0
投票

试试这个。 Type ValueOf 将枚举的每个键映射到其值,然后将这些类型联合在一起。因此,您可以将此实用程序类型应用于您的枚举以获取其值的并集:

enum Stage {
  STARTED = 1,
  COMPLETED
}

const SystemState = {
  Stage,
}

type ValueOf<T> = T[keyof T];

type StageType = ValueOf<typeof SystemState['Stage']>;
© www.soinside.com 2019 - 2024. All rights reserved.