将打字稿枚举转换为枚举数组

Posted

技术标签:

【中文标题】将打字稿枚举转换为枚举数组【英文标题】:Convert a typescript enum into an array of enums 【发布时间】:2019-03-04 09:14:29 【问题描述】:

我有一个枚举

export enum A
   X = 'x',
   Y = 'y',
   Z = 'z'

我希望将其转换为

[A.X, A.Y, A.Z]

数组的类型是A[]。如何做到这一点?

【问题讨论】:

看***.com/questions/43100718/… @SudhirOjha,你的评论让我找到了正确的答案 【参考方案1】:

您可以使用 Object.keys 来获取枚举的键,并使用它们来获取所有值。

它看起来像这样。

let arr: A[] = Object.keys(A).map(k => A[k])

你可以看到它在工作here。

【讨论】:

我想将类型保留为枚举。我正在相应地编辑您的答案 我相信您也可以使用Object.values(A),以避免不必要的映射。 Enum 被编译为一个对象,这就是为什么 keysvalues 方法都在这里工作。 Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof A'. No index signature with a parameter of type 'string' was found on type 'typeof A'.【参考方案2】:

您可以使用 Object.values 来获取枚举的值

enum A 
  X = 'x',
  Y = 'y',
  Z = 'z'

let arr = Object.values(A)
console.log(arr);

【讨论】:

(Matt Leonowicz assumed so)

以上是关于将打字稿枚举转换为枚举数组的主要内容,如果未能解决你的问题,请参考以下文章

打字稿枚举值作为数组

我可以使用打字稿将对象键限制为枚举值吗?

具有值和显示名称的typescript枚举

将firebase json转换为打字稿数组

打字稿将数组转换为 JSON

将 JSON 转换为数组打字稿