如何在打字稿中访问枚举?给出错误“元素隐式具有任何类型,因为索引表达式不是数字类型”

1 javascript enums typescript react-native

export enum r {
  color1 = "Red"
  color2 = "green"
  color3 = "blue"
}

ar = ["color1", "color2"];
ar.map(e => {
  if (r[e as any] !== undefined) {
    return r[e]
  }
})
Run Code Online (Sandbox Code Playgroud)

上面的语句给出“元素隐式具有任何类型,因为索引表达式不是数字类型”

Kev*_*off 6

您需要输入arwithkeyof typeof让 TypeScript 知道您的数组包含枚举中的值:

export enum r {
  color1 = "Red",
  color2 = "green",
  color3 = "blue",
}

const ar: (keyof typeof r)[] = ["color1", "color2"];
const newVal = ar.map((e) => {
  if (r[e] !== undefined) {
    return r[e];
  }
});
Run Code Online (Sandbox Code Playgroud)

这是关于它的一个很好的深入答案