ts中的enum 如何动态的读取

enum test{
  type='aa',
  r='bb',
  g=200
}

var a = 'aa';

console.log(test[a]);

报错了,但是想实现类似这种效果。

阅读 8.9k
4 个回答

把var改成const试试

var a = 'type' as const;

解释:枚举的 key 是 string literal 类型而非 string,故报错。默认情况下 a 会被推断成 string 类型,如果想要 a 的类型被推断成 string literal 需要加上 as const 后缀指令。

我写错了是 'aa'

test[aa as keyof typeof test]