Given the following enums:
enum MyFirstEnum {
A = 'A',
B = 'B',
C = 'C'
}
enum MySecondEnum {
C = 'C',
D = 'D',
E = 'E'
}
What is the proper way of merging them? Note that they contain overlap in the key C = 'C'
, so just MyFirstEnum | MySecondEnum
MyFirstEnum | MySecondEnum
may cause some trouble, for example:
type BothEnums = MyFirstEnum | MySecondEnum
const myRecord: Partial<Record<BothEnums, string>> = {}
const someKey = MyFirstEnum.C
myRecord[someKey] = 'some value' // ❌ Property '[MyFirstEnum.C]' does not exist on type 'Partial<Record<BothEnums, string>>'
If I understood correctly from this question How to merge two enums in TypeScript , Typescript does not handle different enums with duplicate keys and values well.
But if one really needs to merge enums with this overlap, how to do it with no (or less) further problems?
Is that would work?
type BothEnums = {[key in keyof typeof MyFirstEnum | keyof typeof MySecondEnum] :
key extends keyof typeof MyFirstEnum ? key extends keyof typeof MySecondEnum ? (typeof MySecondEnum[key] | typeof MyFirstEnum[key]) :
typeof MyFirstEnum[key] : key extends keyof typeof MySecondEnum ? typeof MySecondEnum[key] : never}
equivalent to:
type BothEnums = {
A: MyFirstEnum.A;
B: MyFirstEnum.B;
C: MyFirstEnum.C | MySecondEnum.C;
D: MySecondEnum.D;
E: MySecondEnum.E;
}
Needed to be call with keyof:
const myRecord: Partial<Record<keyof BothEnums, string>> = {}
const someKey1 = MyFirstEnum.C
const someKey2 = MySecondEnum.C
myRecord[someKey1] = 'some value 1'
myRecord[someKey2] = 'some value 2'
console.log(JSON.stringify(myRecord)) // "{"C":"some value 2"}"
But I would personally prefer this option:
const MyFirstEnumDef = ['A','B','C'] as const satisfies readonly string[];
const MySecondEnumDef = ['C','D','E'] as const satisfies readonly string[];
type MyFirstEnum = typeof MyFirstEnumDef[number]
type MySecondEnum = typeof MySecondEnumDef[number]
type BothEnums = MyFirstEnum | MySecondEnum
const myRecord: Partial<Record<BothEnums, string>> = {}
const someKey1 = "C"
myRecord[someKey1] = 'some value 1'
console.log(JSON.stringify(myRecord)) // "{"C":"some value 1"}"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.