如何获取枚举值索引?

时间:2020-10-13 13:27:47

标签: typescript lodash

有一个枚举:

export enum MY_ENUM {
  numberOne = 'one',
  numberTwo = 'two',
}

还有一种获取给定值索引的方法:

const x = values(MY_ENUM).indexOf('two');

使用TypeScript 3.5.3可以正常工作,而使用4.0.3可以抛出:

Type error: Argument of type 'string' is not assignable to parameter of type 'MY_ENUM'

如何解决?

1 个答案:

答案 0 :(得分:1)

您能只从enum获取密钥吗?

例如

enum MY_ENUM {
  numberOne = 'one',
  numberTwo = 'two',
}
const position = Object.keys(MY_ENUM)
  .map((k) => MY_ENUM[k])
  .indexOf('one');