4

Say there is an

enum ArrowKey{
  Up = "ArrowUp",
  Right = "ArrowRight",
  Down = "ArrowDown",
  Left = "ArrowLeft"
}

Now when receiving a KeyboardEvent with e.key "ArrowUp" how is it easily checked that this string value exists in the enum? And how to pick out the right enum value afterwards?

4
  • why not use a dictionary? Commented Mar 2, 2018 at 15:41
  • Because I need the enum value to be passed into a method and this method will have a switch statement for the enum to figure out what to do next. Consider not to downvote when you have such little reputation... Commented Mar 2, 2018 at 15:50
  • I don't understand what exactly you're trying to do. You can use e.key directly for your switch because when e.key === 'ArrowUp' then e.key === ArrowKey.Up. You could even consider using a const enum. Commented Mar 2, 2018 at 16:41
  • First I would like to check if the string value from e.key which is "ArrowUp" exists as an enum value in the ArrowKey enum. If so, I would like to get the corresponding enum value -> ArrowKey.up Commented Mar 2, 2018 at 16:43

1 Answer 1

7

The following function will return enum value corresponding to pressed arrow key or null if this key is not defined inside that enum.

getEnumValue(event): ArrowKey | null {
  const pressedKey = event.key;
  const keyEnum = Object.keys(ArrowKey).find(key => ArrowKey[key] === pressedKey);
  return ArrowKey[keyEnum] || null;
}

demo: https://stackblitz.com/edit/angular-dmqwyf?embed=1&file=app/app.component.html

EDIT: one-line equivalent (ES 2017)

getEnumValue(event): ArrowKey | null {
  return Object.values(ArrowKey).includes(event.key) ? event.key : null;
}
Sign up to request clarification or add additional context in comments.

2 Comments

You might need to typecast for that second suggestion given that event.key is going to return a string not an ArrowKey
@jlogan you are right. Should be: getEnumValue(event): ArrowKey | null { return Object.values(ArrowKey).includes(event.key as ArrowKey) ? event.key : null; }

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.