check if enum is valid in typescript

To check if an enum is valid in TypeScript, one approach is to use a switch statement on the enum value and include a default case to catch any unexpected values.

Here is an example:

index.ts
enum Color {
  Red = 1,
  Green = 2,
  Blue = 3
}

function isColorValid(value: any): boolean {
  switch (value) {
    case Color.Red:
    case Color.Green:
    case Color.Blue:
      return true;
    default:
      return false;
  }
}

console.log(isColorValid('Red')); // false
console.log(isColorValid(1)); // true
console.log(isColorValid(4)); // false
357 chars
21 lines

In this example, we define an enum called Color with three values. We then define a function isColorValid that takes a value of any type and returns a boolean indicating whether the value is a valid Color.

Inside the function, we use a switch statement to check whether the value is one of the valid Color values. We include a default case to catch any values that are not explicitly handled in the switch statement.

We can then test the function with different input values to see whether it correctly identifies valid and invalid Color values.

gistlibby LogSnag