Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
type ButtonType = 'primary' | 'secondary' | 'link';
// First we will define a Record indexed by ButtonType
// Record type is smart enough to spot if we miss a ButtonType
// in its definition, if we leave e.g. the 'link', we will get an error
const butonTypesMap: Record<ButtonType, true> = {
primary: true,
secondary: true,
link: true
// Then we take all the keys of our map and cast them to ButtonType
const buttonTypes: ButtonType[] = Object.keys(buttonTypeMap) as ButtonType[];
// This hack will only work for string union types though.
// It will not save you any typing and maybe even more importantly
// will intoduce type casting and an extra const.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment