Check if value exists in enum in TypeScript

前端 未结 8 1569
悲哀的现实
悲哀的现实 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 ((Object).values(Vehicle).includes('car')) {
        // Do stuff here
    }
    

提交回复
热议问题