How to merge two enums in TypeScript

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

    Enums, interfaces and types - a working solution for merging enums

    What's confusing here is types vs. values.

    • If you define a value (let, const etc.) it will have a value plus some computed but not separately named type.
    • If you define a type or interface, it will create a named type but that will not be outputted or considered in the final JS in any way. It only helps when writing your app.
    • If you create an enum in Typescript, it creates a static type name that you can use plus a real object outputted to JS that you can use.

    From the TS handbook:

    Using an enum is simple: just access any member as a property off of the enum itself, and declare types using the name of the enum.

    So, if you Object.assign() two enums, it will create a new, merged value (object), but not a new named type.

    Since it's not an enum anymore, you lose the advantage of having a value and a named type, but you can still create a separate type name as a workaround.

    Fortunately, you can have the same name for the value and the type, and TS will import both if you export them.

    // This creates a merged enum, but not a type
    const Animals = Object.assign({}, Mammals, Reptiles);
    
    // Workaround: create a named type (typeof Animals won't work here!)
    type Animals = Mammals | Reptiles;
    

    TS playground link

提交回复
热议问题