TypeScript Version: 2.4.2
Code
enum Colors {
Red = 'RED',
Green = 'GREEN',
Blue = 'BLUE',
}
const test: string = 'Red';
Colors[test];
Workaround
enum Colors {
Red = 'RED',
Green = 'GREEN',
Blue = 'BLUE',
}
const test: any = 'Red';
Colors[test];
Expected behavior:
Should compile
Actual behavior:
error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.
There is an issue #11773 demonstrating it with a "normal" enum.
just remove the type annotation:
const test = 'Red';
// alternative
const test: keyof Colors = 'Red';
Seems we never did anything different with the indexing rules for string enums, which is bad. Colors[32]
is extremely suspect.
I found the fix!
const test: keyof typeof Colors = 'Red';
I had the same problem and that fixed it.
I've a different repro case.
Playground link: https://www.typescriptlang.org/play/index.html#src=enum%20ContentType%20%7B%0D%0A%20%20Article%20%3D%20'a'%2C%0D%0A%20%20Video%20%3D%20'v'%0D%0A%7D%0D%0A%0D%0Aconst%20args%20%3D%20%7B%20type%3A%20%5B%20'Article'%2C%20'Video'%20%5D%20%7D%0D%0A%0D%0Awindow.alert(args.type.map(t%20%3D%3E%20ContentType%5Bt%5D))
Source:
enum ContentType {
Article = 'a',
Video = 'v'
}
const args = { type: [ 'Article', 'Video' ] }
window.alert(args.type.map(t => ContentType[t]))
Workaround:
As @fmpierce suggests, rewriting t
as (t: keyof typeof ContentType)
does fix the compilation issue. Obviously, the amount of code that needs to be written for the workaround is unacceptable.
Expected behavior:
The compiler should be able to figure out that the intent is keyof typeof ContentType
.
Actual behavior:
error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.
Thanks, @fmpierce! Used your solution in the following:
Object.keys(Colors).map((color: keyof typeof Color): JSX.Element => {
return (
<div
key={color}
onClick={() => this._methodThatTakesAnEnum(Color[color])}
>
{ Util.functionThatTakesAString(color) }
</div>
);
});
The anon function signature color: string
causes the same error when trying to access Color[color]
.
Most helpful comment
I found the fix!
const test: keyof typeof Colors = 'Red';
I had the same problem and that fixed it.