'How can I exclude some items from a merged enum in TypeScript?

I defined the following enums:

enum myEnum {
    a = 1,
    b = 2
}

enum mySecondEnum {
    c = 3,
    d = 4
}

and later on merged them together, to form a single enum:

const mergedEnum = {...myEnum, ...mySecondEnum};
type mergedEnum = typeof mergedEnum;

If I now want to exclude a specific value from the merged enum, I get a strange typescript error, which I can not comprehend:

/** Type '{ [x: number]: string; c: mySecondEnum.c; d: mySecondEnum.d; a: myEnum.a; b: myEnum.b; }' does not satisfy the constraint 'string | number | symbol'.
  Type '{ [x: number]: string; c: mySecondEnum.c; d: mySecondEnum.d; a: myEnum.a; b: myEnum.b; }' is not assignable to type 'symbol'.(2344) **/
const mergedOmitedEnum: Record<Exclude<mergedEnum, 1>, number> = {
    ...
}
**/

However, using the same approach, with a non merged enum, works as expected:

/** This does work as expected, it omits the "1" from "myEnum" */
const simpleOmitedEnum: Record<Exclude<myEnum, 1>, number> = {
    "2": 1
}

How can I merge multiple enums, and later on omit some values from the merged result set?

Here's a playground link



Solution 1:[1]

The simplest way to create the mergedEnum type would be to just union the two different enums

type mergedEnum = myEnum | mySecondEnum;

Playground Link

Normally you would want to get type of values in the mergedEnum constant, typeof mergedEnum is the type of the constant itself. To get the types of all values normally we could do typeof mergedEnum[keyof typeof mergedEnum]. But because the enum objects have index signatures from number to string, the merged object will also have this signature. Since the original enums are number enums, we could just remove the extra string in the union we get from typeof mergedEnum[keyof typeof mergedEnum]

type mergedEnum =  Exclude<typeof mergedEnum [keyof typeof mergedEnum ], string>;

Playground Link

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 T.J. Crowder