Last active
January 4, 2019 16:17
-
-
Save mheiber/cc4cc397322441692e5fa70fc37c96f1 to your computer and use it in GitHub Desktop.
type-safe enums
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 KeyMirror<T extends keyof any> = { | |
[K in T]: K | |
} | |
// simple approach | |
type FileTypes1 = 'ECMAScript' | 'TypeScript' | |
const FILE_TYPES_1: KeyMirror<FileTypes1> = { | |
ECMAScript: 'ECMAScript', | |
TypeScript: 'TypeScript' | |
} | |
const a: FileTypes1 = 'ECMAScript' // type-checks | |
const b: FileTypes1 = 'will type error' // compile-time error | |
// fancy approach | |
function keyMirror<T extends keyof any>(values: T[]): KeyMirror<T> { | |
const x = {} as KeyMirror<T> | |
values.forEach(key => { | |
x[key] = key; | |
}) | |
return x; | |
} | |
const FILE_TYPES = keyMirror(['ECMAScript', 'TypeScript']) | |
type FileType = keyof typeof FILE_TYPES | |
const x: FileType = 'ECMAScript' // type-checks | |
const y: FileType = 'will type error' // compile-time error | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment