Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check string value in enum TypeScript

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?

like image 496
Bernoulli IT Avatar asked Mar 07 '23 18:03

Bernoulli IT


1 Answers

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;
}
like image 106
Wilhelm Olejnik Avatar answered Mar 16 '23 14:03

Wilhelm Olejnik