How to check if a given string key exists in Enum

后端 未结 4 1853
一生所求
一生所求 2020-12-16 12:08

I have an enum defined like this

export enum someEnum {
    None = \'\',
    value1 = \'value1\',
    value2 = \'value2\',
         


        
4条回答
  •  情歌与酒
    2020-12-16 12:42

    Typescript enums are a little annoying because they have two sides - the atom used to name a value, and the actual value. These each have a different way to check them.

    Let's use an example enum that represents actions a content blocker can take. We'll get a kebab-case value from our API but want to use a camelCase value in TS:

    enum ActionType {
      block = "block",
      cssDisplayNone = "css-display-none",
      ignorePreviousRules = "ignore-previous-rules"
    }
    

    Now if we wanted to check if it was valid to say ActionType.cssDisplayNone in our code, we can check that with the in operator. However, if we have a value from an API and we want to see if the value we got is an ActionType, that won't work!

    const canBlockCss = 'cssDisplayNone' in ActionType; // Returns true
    const isValidAction = 'css-display-none' in ActionType; // Returns false!
    

    In this case, we need to write a type guard:

    function isActionType(test: any): test is ActionType {
        return (Object.values(ActionType).indexOf(test) !== -1);
    }
    
    const isValidAction = isActionType('css-display-none') // Returns true
    

    This has the added bonus that if you have a variable of unknown type and pass it to a type guard, the return value will be included in Typescript's understanding of the variable, allowing you to cast it at the same time as you check it.

提交回复
热议问题