What are enum Flags in TypeScript?

后端 未结 5 1235
死守一世寂寞
死守一世寂寞 2021-01-30 17:08

I\'m learning TypeScript using this ebook as a reference. I\'ve checked the TypeScript Official Documentation but I don\'t find information about enum flags.

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 17:31

    The official documentation has this example that I will add some details that are crucial to use enum and flags.

    enum FileAccess {
        None,
        Read    = 1 << 1,
        Write   = 1 << 2,
    }
    

    In TypeScript, you can assign a value directly with =

    let x:FileAccess = FileAccess.Read;
    

    But this might override previous values. To get around that you can use |= to append a flag.

    x |= FileAccess.Write;
    

    At this point, the variable x is Read and Write. You can remove a value by using the ampersand and tilde:

    x &= ~FileAccess.Read;
    

    Finally, you can compare to see if one of the value is set to the variable. The accepted answer is not right. It should not just use the ampersand symbol but also check with === to the desired value. The reason is the ampersand returns a number, not a boolean.

    console.log(FileAccess.Write === (x & FileAccess.Write)); // Return true
    console.log(FileAccess.Read === (x & FileAccess.Read)); // Return false
    

提交回复
热议问题