How to merge two enums in TypeScript

前端 未结 6 1726
無奈伤痛
無奈伤痛 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:14

    A TypeScript enum not only contains the keys you define but also the numerical inverse, so for example:

    Mammals.Humans === 0 && Mammals[0] === 'Humans'
    

    Now, if you try to merge them -- for example with Object#assign -- you'd end up with two keys having the same numerical value:

    const AnimalTypes = Object.assign({}, Mammals, Reptiles);
    console.log(AnimalTypes.Humans === AnimalTypes.Snakes) // true
    

    And I suppose that's not what you want.

    One way to prevent this, is to manually assign the values to the enum and make sure that they are different:

    enum Mammals {
        Humans = 0,
        Bats = 1,
        Dolphins = 2
    }
    
    enum Reptiles {
        Snakes = 3,
        Alligators = 4,
        Lizards = 5
    }
    

    or less explicit but otherwise equivalent:

    enum Mammals {
        Humans,
        Bats,
        Dolphins
    }
    
    enum Reptiles {
        Snakes = 3,
        Alligators,
        Lizards
    }
    

    Anyway, as long as you make sure that the enums you merge have different key/value sets you can merge them with Object#assign.

    Playground Demo

提交回复
热议问题