check if string is in enum in typescript

You can use a conditional statement to check if a string value is a key of an enum type in TypeScript. Here's an example:

index.ts
enum Fruit {
  APPLE = 'apple',
  BANANA = 'banana',
  ORANGE = 'orange'
}

const myFruit: string = 'apple';

if (myFruit in Fruit) {
  console.log(`${myFruit} is a valid fruit.`);
} else {
  console.log(`${myFruit} is NOT a valid fruit.`);
}
243 chars
14 lines

In this example, we have an enum called Fruit with three keys: APPLE, BANANA, and ORANGE. We also have a string variable myFruit that we want to check is a valid fruit. We use the in keyword to check if myFruit exists as a key within the Fruit enum. If it does, we log that it's a valid fruit; otherwise, we log that it's not a valid fruit.

gistlibby LogSnag