Youp Bernoulli
Youp Bernoulli

Reputation: 5635

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?

Upvotes: 4

Views: 9285

Answers (1)

Wilhelm Olejnik
Wilhelm Olejnik

Reputation: 2507

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;
}

Upvotes: 7

Related Questions