【问题标题】: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[]。如何做到这一点?

【问题讨论】:

标签: typescript


【解决方案1】:

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

它看起来像这样。

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

你可以看到它在工作here。

【讨论】:

  • 我想将类型保留为枚举。我正在相应地编辑您的答案
  • 我相信您也可以使用Object.values(A),以避免不必要的映射。 Enum 被编译为一个对象,这就是为什么 keys 和 values 方法都在这里工作。
  • 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);

【讨论】:

猜你喜欢
  • 2018-07-05
  • 2019-10-30
  • 2013-01-17
  • 2020-04-30
  • 1970-01-01
  • 2019-09-25
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多