TypeScript Version: 2.5.3
It could be I stumbled on something I simply don't understand, but it seems like this should work:
Code
enum Color {
RED = "RED",
BLUE = "BLUE",
GREEN = "GREEN"
}
type ColorMap = {
[P in Color]: number; // type ColorMap = { RED: number; BLUE: number; GREEN: number; }
}
declare const color: Color;
map[color] // Error: Element implicitly has an 'any' type because type 'ColorMap' has no index signature.
All of the following work:
declare const map: ColorMap;
map[Color.RED] // OK
const red: Color = Color.RED;
map[red] // OK
declare const color: keyof typeof Color;
map[color] // OK -- I don't know why this works
Expected behavior:
map[color] to work and give return type of number
Actual behavior:
map[color] // Error: Element implicitly has an 'any' type because type 'ColorMap' has no index
More stuff I don't understand:
declare const color: Color.RED | Color.BLUE | Color.GREEN;
map[color] // Error: Element implicitly has an 'any' type because type 'ColorMap' has no index signature.
declare const color: Color.RED | Color.BLUE | "GREEN";
map[color] // OK
I think my confusion lies with how the compiler actually "sees" the enum type... I thought that string enum was equivalent to the old string literal type + namespace workaround:
type Color = "RED" | "BLUE" | "GREEN"
namespace Color { export const RED = "RED"; export const BLUE = "BLUE"; export const GREEN = "GREEN"; }
type ColorMap = {
[P in Color]: number;
}
declare const map: ColorMap;
map[Color.RED] // OK
const red: Color = Color.RED;
map[red] // OK
declare const color: Color;
map[color] // Ok
But it obviously is a different thing that isn't as intuitive to me...
I've also found this very counterintuitive. The workaround was more verbose but was expressive and allowed for very convenient consumption.
Duplicate of #16760. Should be fixed by https://github.com/Microsoft/TypeScript/pull/18029
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
Most helpful comment
Duplicate of #16760. Should be fixed by https://github.com/Microsoft/TypeScript/pull/18029