Check if value exists in enum in TypeScript

前端 未结 8 1522
悲哀的现实
悲哀的现实 2020-11-29 17:38

I recieve a number type = 3 and have to check if it exists in this enum:

export const MESSAGE_TYPE = {
    INFO: 1,
    SUCCESS: 2,
    WARNING:         


        
相关标签:
8条回答
  • 2020-11-29 17:48

    If you want this to work with string enums, you need to use Object.values(ENUM).includes(ENUM.value) because string enums are not reverse mapped, according to https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html:

    Enum Vehicle {
        Car = 'car',
        Bike = 'bike',
        Truck = 'truck'
    }
    

    becomes:

    {
        Car: 'car',
        Bike: 'bike',
        Truck: 'truck'
    }
    

    So you just need to do:

    if (Object.values(Vehicle).includes('car')) {
        // Do stuff here
    }
    

    If you get an error for: Property 'values' does not exist on type 'ObjectConstructor', then you are not targeting ES2017. You can either use this tsconfig.json config:

    "compilerOptions": {
        "lib": ["es2017"]
    }
    

    Or you can just do an any cast:

    if ((<any>Object).values(Vehicle).includes('car')) {
        // Do stuff here
    }
    
    0 讨论(0)
  • 2020-11-29 17:49
    enum ServicePlatform {
        UPLAY = "uplay",
        PSN = "psn",
        XBL = "xbl"
    }
    

    becomes:

    { UPLAY: 'uplay', PSN: 'psn', XBL: 'xbl' }
    

    so

    ServicePlatform.UPLAY in ServicePlatform // false
    

    SOLUTION:

    ServicePlatform.UPLAY.toUpperCase() in ServicePlatform // true
    
    0 讨论(0)
  • 2020-11-29 17:56

    For anyone who comes here looking to validate if a string is one of the values of an enum and type convert it, I wrote this function that returns the proper type and returns undefined if the string is not in the enum.

    function keepIfInEnum<T>(
      value: string,
      enumObject: { [key: string]: T }
    ) {
      if (Object.values(enumObject).includes((value as unknown) as T)) {
        return (value as unknown) as T;
      } else {
        return undefined;
      }
    }
    

    As an example:

    enum StringEnum {
      value1 = 'FirstValue',
      value2 = 'SecondValue',
    }
    keepIfInEnum<StringEnum>('FirstValue', StringEnum)  // 'FirstValue'
    keepIfInEnum<StringEnum>('OtherValue', StringEnum)  // undefined
    
    0 讨论(0)
  • 2020-11-29 18:03
    export enum UserLevel {
      Staff = 0,
      Leader,
      Manager,
    }
    
    export enum Gender {
      None = "none",
      Male = "male",
      Female = "female",
    }
    

    Difference result in log:

    log(Object.keys(Gender))
    =>
    [ 'None', 'Male', 'Female' ]
    
    log(Object.keys(UserLevel))
    =>
    [ '0', '1', '2', 'Staff', 'Leader', 'Manager' ]
    

    The solution, we need to remove key as a number.

    export class Util {
      static existValueInEnum(type: any, value: any): boolean {
        return Object.keys(type).filter(k => isNaN(Number(k))).filter(k => type[k] === value).length > 0;
      }
    }
    

    Usage

    // For string value
    if (!Util.existValueInEnum(Gender, "XYZ")) {
      //todo
    }
    
    //For number value, remember cast to Number using Number(val)
    if (!Util.existValueInEnum(UserLevel, 0)) {
      //todo
    }
    
    0 讨论(0)
  • 2020-11-29 18:05

    This works only on non-const, number-based enums. For const enums or enums of other types, see this answer above


    If you are using TypeScript, you can use an actual enum. Then you can check it using in.

    export enum MESSAGE_TYPE {
        INFO = 1,
        SUCCESS = 2,
        WARNING = 3,
        ERROR = 4,
    };
    
    var type = 3;
    
    if (type in MESSAGE_TYPE) {
    
    }
    

    This works because when you compile the above enum, it generates the below object:

    {
        '1': 'INFO',
        '2': 'SUCCESS',
        '3': 'WARNING',
        '4': 'ERROR',
        INFO: 1,
        SUCCESS: 2,
        WARNING: 3,
        ERROR: 4
    }
    
    0 讨论(0)
  • 2020-11-29 18:07

    TypeScript v3.7.3

    export enum YourEnum {
       enum1 = 'enum1',
       enum2 = 'enum2',
       enum3 = 'enum3',
    }
    
    const status = 'enumnumnum';
    
    if (!(status in YourEnum)) {
         throw new UnprocessableEntityResponse('Invalid enum val');
    }
    
    0 讨论(0)
提交回复
热议问题