0

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

1
  • 1
    The problem is that Type[t] could give you the enum value or the enum key: Type['a'] == 'value_a' and Type['value_a'] == 'a'. Only one of these is Type.a. This is because enum E {A, B} actually generates E = { 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. Commented Sep 13, 2019 at 11:33

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.