Skip to content

Instantly share code, notes, and snippets.

@mheiber
Last active January 4, 2019 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mheiber/cc4cc397322441692e5fa70fc37c96f1 to your computer and use it in GitHub Desktop.
Save mheiber/cc4cc397322441692e5fa70fc37c96f1 to your computer and use it in GitHub Desktop.
type-safe enums
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