export enum r {
color1 = "Red"
color2 = "green"
color3 = "blue"
}
ar = ["color1", "color2"];
ar.map(e => {
if (r[e as any] !== undefined) {
return r[e]
}
})
Above statement giving "Element implicitly has an any type because index expression is not of type number"
You need to type ar
with keyof typeof
to let TypeScript know your array contains values from your enum:
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];
}
});
Here is a good in-depth answer about it
You do not have commas after every item in your enum. However, the following is how you can typecast the argument to be type of key of the enum:
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;}
})
The problem with your approach is you are using map and you need to return in every iteration. What you need is filter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.