Check if value exists in enum in TypeScript

前端 未结 8 1523
悲哀的现实
悲哀的现实 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 18:12

    There is a very simple and easy solution to your question:

    var districtId = 210;
    
    if (DistrictsEnum[districtId] != null) {
    
    // Returns 'undefined' if the districtId not exists in the DistrictsEnum 
        model.handlingDistrictId = districtId;
    }
    
    0 讨论(0)
  • 2020-11-29 18:15

    According to sandersn the best way to do this would be:

    Object.values(MESSAGE_TYPE).includes(type as MESSAGE_TYPE)
    
    0 讨论(0)
提交回复
热议问题