Created
September 12, 2023 14:25
-
-
Save mharj/76f6b8b8b0061d7198c167e97be7393c to your computer and use it in GitHub Desktop.
two way numeric enum setup
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
| enum Demo { | |
| Eka = 100, | |
| Toka, | |
| } | |
| type DemoKey = keyof typeof Demo; | |
| // for validations | |
| const demoKeys = Object.values(Demo).filter((v) => isNaN(Number(v))) as [DemoKey]; | |
| const demoValues = Object.values(Demo).filter((v) => !isNaN(Number(v))) as [Demo]; | |
| function getDemoValue(value: Demo | DemoKey): Demo { | |
| return (demoKeys.includes(value as DemoKey) ? Demo[value] : value) as Demo; | |
| } | |
| function getDemoName(value: Demo | DemoKey): DemoKey { | |
| return (demoKeys.includes(value as DemoKey) ? value : Demo[value]) as DemoKey | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment