Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check to see if string exists in Enum

Tags:

typescript

This is not a duplicate of: Check if value exists in enum in TypeScript that checks a type Enum against the Enum values.

There are no other posts regarding TypeScript how one would check a string or string literal against an Enum. The reason being is that I am receiving data via an API, so it's original type is of a string.

Code:

enum Method {
    Get = 'get',
    Put = 'put',
    Post = 'post',
    Patch = 'patch',
    Delete = 'delete'
}

console.log(Method);
console.log('get' in Method);
console.log(Object.values(Method));
console.log(Object.values(Method).includes('get'));

Output:

src/libs/async-express/test.ts:12:44 - error TS2345: Argument of type '"get"' is not assignable to parameter of type 'Method'.

12 console.log(Object.values(Method).includes('get'));

In Java it would be done like this:

public static boolean contains(String test) {
    for (Choice c : Choice.values()) {
        if (c.name().equals(test)) {
            return true;
        }
    }
    return false;
}

Any standard ways of doing this in TypeScript.

like image 373
basickarl Avatar asked Sep 06 '25 03:09

basickarl


2 Answers

The easiest way (as you have noticed yourself) is to use casting.

// Implicit cast
const allMethods: string[] = Object.values(Method);
console.log(allMethods.includes("get"));

// Explicit cast
console.log((Object.values(Method) as string[]).includes("get"));
like image 177
petraszd Avatar answered Sep 07 '25 23:09

petraszd


To avoid having to cast the type, you can add a type annotation to Object.values- this just widens it from Method[].

However if you need to successfully narrow the type, you should use a type guard; otherwise you won't be able to pass the variable to other functions that only accept Method.

// type guard fn
const isMethod = (maybeMethod: string): maybeMethod is Method => {
  // explicityly type the values of Method as an array of strings,
  // so they can be compared to possible invalid methods
  const validMethods: string[] = Object.values(Method);
  return validMethods.includes(maybeMethod);
};

// fn to demonstrate narrowing behavior
const foo = (maybeMethod: string) => {
  if (isMethod(maybeMethod)) {
    // compiler successfully narrows the type, and
    const clone = maybeMethod; // (parameter) maybeMethod: Method
  }

  if (Object.values(Method).includes(maybeMethod as Method)) {
    // the type has not actually been narrowed.
    // maybeMethod is still just a string.
    const clone = maybeMethod; // (parameter) maybeMethod: string
  }
};

like image 20
kschaer Avatar answered Sep 07 '25 22:09

kschaer