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

问题描述 投票:0回答:2
export enum r {
  color1 = "Red"
  color2 = "green"
  color3 = "blue"
}

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

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

javascript typescript react-native enums
2个回答
7
投票

您需要输入

ar
keyof 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];
  }
});

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


2
投票

枚举中的每个项目后面都没有逗号。但是,以下是如何将参数类型转换为枚举的键类型:

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

const ar = ["color1","color2"];
const new_ar = ar.filter(e => {
    if (e in r && r[e as keyof typeof r]) 
    {return true;}
    else {return false;}
})

您的方法的问题是您正在使用地图,并且您需要在每次迭代中返回。你需要的是过滤器。

© www.soinside.com 2019 - 2024. All rights reserved.