Created
May 15, 2019 15:58
-
-
Save takayukioda/7cc70ec8886c32ec0be2bc58b5123497 to your computer and use it in GitHub Desktop.
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
| // Type strict; couldn't find a good use case | |
| // from https://stackoverflow.com/a/49894514 | |
| const strictKeys = <T>(anenum: T): (keyof T)[] => | |
| Object.keys(anenum).filter((k) => typeof anenum[k] === 'number') as any | |
| // Only available for number enum | |
| // from https://github.com/Microsoft/TypeScript/issues/17198#issuecomment-315400819 | |
| const nkeys = <T>(anenum: T): string[] => | |
| Object.keys(anenum).filter((k) => typeof anenum[k] === 'number') | |
| // Work both for number and string enum; not useful for number enum though | |
| const skeys = <T>(anenum: T): string[] => | |
| Object.keys(anenum).filter((k) => typeof anenum[k] === 'string') | |
| // Work both for number and string enum | |
| // Throws an error when accessing non-existing property | |
| const get = <T>(anenum: T, key: string): T[keyof T] => | |
| Object.keys(anenum).map((p) => [p.toLowerCase(), anenum[p]]).find(([k, _]) => k === key)[1] | |
| enum Perm { Read, Write, Execute } | |
| enum Color { White = '#fff', Black = '#000', Red = '#f00', Green = '#0f0', Blue = '#00f' } | |
| console.log(nkeys(Perm)) | |
| // --> [ 'Read', 'Write', 'Execute' ] | |
| console.log(skeys(Perm)) | |
| // --> [ '0', '1', '2' ] | |
| console.log(nkeys(Color)) | |
| // --> [] | |
| console.log(skeys(Color)) | |
| // --> [ 'White', 'Black', 'Red', 'Green', 'Blue' ] | |
| console.log(get(Perm, 'read')) | |
| // --> 0 | |
| console.log(get(Perm, '2')) | |
| // --> 'Execute' | |
| console.log(get(Perm, 1)) | |
| // --> Compile Error | |
| console.log(get(Color, 'black')) | |
| // --> '#000' | |
| console.log(get(Color, '#0f0')) | |
| // --> Runtime Error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment