0

On an angular 12 app I have the enum:

export enum Policy {
  Admin,
  Manager
} 

I try to define a variable of type Policy as follows:

let policy: Policy = Policy[route.data.policy as string]; 

The type of route.data.policy is any. But I get the error:

Element implicitly has an 'any' type because index expression is not of type 'number'.

How can to parse the value of route.data.policy which would be 'Admin' or 'Manager' to enum?

JSON Derulo
  • 9,780
  • 7
  • 39
  • 56
Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • 2
    TL;DR: `let policy: Policy = Policy[route.data.policy as keyof typeof Policy];` [TS Playground](https://www.typescriptlang.org/play?ssl=8&ssc=10&pln=9&pc=3#code/MYewdgzgLgBATiArlApjAvDA3gKBjAEwEMoiAubPfGABxABsBLYATwoHIBBAgW0bHZUAvjiEBuHCgAedOLBRhEPGAAUGzFpXzc+YADRUAskTBEA5ijiiYOeilh0mrCmqebMrjQG0EyFADpiUn9HDRgiCBgAaxQWEAAzGCgWGhQE1XVWAF0xIA) – Heretic Monkey Aug 23 '21 at 17:10

2 Answers2

0

What if you type route.data.policy as a Policy? Then you can just have,

let policy: Policy = route.data.policy; 
David Kidwell
  • 600
  • 1
  • 6
  • 15
0

You could just add a value to the keys so Manager = 'Manager' this converts the enum so it takes strings in the [] brackets instead of the default numbers based on index.

h0p3zZ
  • 690
  • 3
  • 16