Last active
April 11, 2022 14:08
-
-
Save kraftdorian/eea4abd2d69956951d035bfef05a234c to your computer and use it in GitHub Desktop.
TypeScript enum composition experiments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// based on: | |
// https://github.com/microsoft/TypeScript/issues/17592#issuecomment-320805415 | |
// https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums | |
enum GlobalEnum {} | |
// example enum 1 | |
enum Example1 { | |
A = 'A', | |
B = 'B' | |
} | |
// example enum 2 | |
enum Example2 { | |
C = 3, | |
D = 4 | |
} | |
// https://github.com/microsoft/TypeScript/issues/17592#issuecomment-320805415 | |
function composeEnum< | |
Enum1 extends typeof GlobalEnum, | |
Enum2 extends typeof GlobalEnum | |
>(enum1: Enum1, enum2: Enum2): typeof GlobalEnum & Enum1 & Enum2 { | |
return { ...enum1, ...enum2 } as typeof GlobalEnum & Enum1 & Enum2; | |
} | |
// https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums | |
const ComposedEnum = composeEnum(Example1, Example2); | |
type ComposedEnum = typeof ComposedEnum[keyof typeof ComposedEnum]; | |
// testing | |
function doSomethingWithComposedEnum(input: ComposedEnum) { | |
console.log(input); // note: for some reason can't use enum members on input | |
} | |
doSomethingWithComposedEnum(ComposedEnum.A); // "A" | |
console.log(ComposedEnum.C); // 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment