Last active
January 23, 2021 18:39
-
-
Save RanolP/921975a35d66ae37306c645abfc35c96 to your computer and use it in GitHub Desktop.
Add static method to enum without namespace in TypeScript
This file contains 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
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> }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Enum with Static Method
You can add a static method to TypeScript's enum without losing type safety(but some changes) & autocompleting.
Example