Skip to content

Instantly share code, notes, and snippets.

@RanolP
Last active January 23, 2021 18:39
Show Gist options
  • Save RanolP/921975a35d66ae37306c645abfc35c96 to your computer and use it in GitHub Desktop.
Save RanolP/921975a35d66ae37306c645abfc35c96 to your computer and use it in GitHub Desktop.
Add static method to enum without namespace in TypeScript
type NoConflict<
A extends Record<string | symbol, unknown>,
B extends string | number | symbol
> = { [K in keyof A]: K extends B ? never : A[K] };
type PropsUnion<A> = { [K in keyof A]: A[K] }[keyof A];
export function withMethods<
Origin extends Record<string | symbol, unknown>,
Methods extends Record<string | symbol, unknown>
>(
origin: NoConflict<Origin, 'T'>,
methods: NoConflict<Methods, keyof Origin | 'T'>
): NoConflict<Origin, 'T'> &
NoConflict<Methods, keyof Origin | 'T'> & { T: PropsUnion<Origin> } {
return { ...origin, ...methods, T: (null as unknown) as PropsUnion<Origin> };
}
@RanolP
Copy link
Author

RanolP commented Feb 26, 2019

Enum with Static Method

You can add a static method to TypeScript's enum without losing type safety(but some changes) & autocompleting.

Example

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment