最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to access Enum in typescript ? giving error "Element implicitly has an any type because index expressi

matteradmin6PV0评论
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"

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"

Share Improve this question edited Jan 14, 2021 at 16:01 uminder 26.2k6 gold badges43 silver badges89 bronze badges asked Jan 14, 2021 at 15:47 user9485480user9485480 311 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

You need to type ar with keyof typeof to let TypeScript know your array contains keys 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 mas 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.

Post a comment

comment list (0)

  1. No comments so far