I’d like to use a TypeScript enum with string values as Map key:
enum Type {
a = 'value_a',
b = 'value_b'
}
const values = new Map<Type, number>();
// set a single value
values.set(Type.a, 1);
This works fine. I can only set keys as defined in the enum. Now I’d like to fill the map, and set values for all entries in the Type enum:
// trying to set all values
for (const t in Type) {
values.set(Type[t], 0); // error
}
This however gives my compile error “Argument of type 'string' is not assignable to parameter of type 'Type'.”
What would be the recommended solution here? Doing a values.set(Type[t] as Type, 0); does the trick, but I’m sure there must be a more elegant solution?
Type[t]could give you the enum value or the enum key:Type['a'] == 'value_a'andType['value_a'] == 'a'. Only one of these isType.a. This is becauseenum E {A, B}actually generatesE = { 0: "A", 1: "B", "A": 0, "B": 1}- it generates the bindings two-way to make sure there aren't duplicates and you can easily access them in either way.