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?

1
  • 2
    TL;DR: let policy: Policy = Policy[route.data.policy as keyof typeof Policy]; TS Playground Commented Aug 23, 2021 at 17:10

2 Answers 2

0

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

let policy: Policy = route.data.policy; 
Sign up to request clarification or add additional context in comments.

4 Comments

You mean let policy: Policy = route.data.policy as Policy? I didn't know I could parse it that way.
That actually might work, but what I meant was to go to wherever you define route.data.policy and type that field as a Policy.
I can't. I am getting route.data.policy from an Angular method.
Ah I see. My mistake. I recommend @Heretic Monkey's solution, then.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.