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?
    – Joseph D.
    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... 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.
    – Tao
    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 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;
}
2
  • 1
    You might need to typecast for that second suggestion given that event.key is going to return a string not an ArrowKey
    – jlogan
    Dec 20, 2019 at 18:31
  • @jlogan you are right. Should be: getEnumValue(event): ArrowKey | null { return Object.values(ArrowKey).includes(event.key as ArrowKey) ? event.key : null; } Jan 8, 2020 at 13:16

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.