Skip to content

Instantly share code, notes, and snippets.

@kraftdorian
Last active April 11, 2022 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kraftdorian/eea4abd2d69956951d035bfef05a234c to your computer and use it in GitHub Desktop.
Save kraftdorian/eea4abd2d69956951d035bfef05a234c to your computer and use it in GitHub Desktop.
TypeScript enum composition experiments
// 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