qqilihq
qqilihq

Reputation: 11454

Using string enum as Map keys

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?

Code in TypeScript Playground

Upvotes: 0

Views: 1645

Answers (1)

Jan Kremeň
Jan Kremeň

Reputation: 92

Use union types instead of enums.

type Type = 'value_a' | 'value_b';
const TYPES: Type[] = ['value_a', 'value_b'];

The bad thing is, that it is little code duplication.

The good thing is, that it's simple and you won't encounter unexpected behavior. At the end of the day, you won't mind little code duplication.

Upvotes: 2

Related Questions