How to merge two enums in TypeScript

前端 未结 6 1784
無奈伤痛
無奈伤痛 2021-01-01 10:30

Suppose I have two enums as described below in Typescript, then How do I merge them

enum Mammals {
    Humans,
    Bats,
    Dolphins
}

enum Reptiles {
             


        
6条回答
  •  北荒
    北荒 (楼主)
    2021-01-01 11:29

    I'm not going to propose a solution to merge to enums (I couldn't find a proper way to do it)

    But if you want something behaving like an enum from the way you consume it, you could still use merged object in javascript.

    enum Mammals {
        Humans = 'Humans',
        Bats = 'Bats',
        Dolphins = 'Dolphins',
    }
    
    enum Reptiles {
      Snakes = 'Snakes',
      Alligators = 'Alligators',
      Lizards = 'Lizards',
    }
    
    const Animals = {
       ...Mammals,
       ...Reptiles,
    }
    
    type Animals = Mammals | Reptiles
    

    Then you could use Animals.Snakes or Animals.Dolphins and both should be properly typed and work as an enum

提交回复
热议问题