2

If I define an enum like this:

enum MyEnum {
    First,
    Second,
};

...and I try to get the value for the "First" element like this:

const value = MyEnum["First"];

...then the type of 'value' is 'number' (as reported by 'typeof value'). However, if I try to get the value this way:

const key: string = "First";
const value = MyEnum[key as any];

...then the type of 'value' is 'string.'

Why is this?

I suspect it has something to do with the 'as any' part because if I leave out just the 'as any' then 'value' is a number, but then the TypeScript compiler yells at me because 'Element implicitly has an any type because index expression is not of type number'

If my index is is a string value (not a literal), is this the 'best' way to get the value as a number?

const value = Number(MyEnum[key as any]);

Thanks!

Auth Infant
  • 1,760
  • 1
  • 16
  • 34
  • Duplicate of [TypeScript TS7015 error when accessing an enum using a string type parameter](https://stackoverflow.com/questions/36316326/typescript-ts7015-error-when-accessing-an-enum-using-a-string-type-parameter) – Herohtar Jul 27 '19 at 06:10

0 Answers0