TS-2 enum

作者: RickyWu585 | 来源:发表于2023-03-08 18:19 被阅读0次
    • enum只用来声明数字就行了,字符串用联合类型最好,enum的值不能是对象类型
    • enum
    enum A = {
      todo = 0,
      done, // 1
      deleted // 2
    }
    
    let status1 = A.todo
    let status2 = 0
    
    • 用 enum 处理权限问题
    enum Permission = {
      None = 0,
      Read = 1 << 0,      // 0001
      Write = 1 << 1,     // 0010
      Delete = 1 << 2,    // 0100
      Manage  = 1 << 3    // 1000
    }
    
    type User = {
      permission: Permission
    }
    
    const user: User = {
      permission: 0b0101
    }
    
    if(CanWrite(user.permission)){
      console.log('有写权限')
    }
    if(CanManage(user.permission)){
      console.log('有管理权限')
    }
    function CanWrite(p:Permission){
      return (p & Permission.Write) === Permission.Write
    }
    function CanManage(p:Permission){
      return (p & Permission.Manage) === Permission.Manage 
    }
    

    相关文章

      网友评论

          本文标题:TS-2 enum

          本文链接:https://www.haomeiwen.com/subject/yjtukdtx.html