Skip to content

Instantly share code, notes, and snippets.

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 janjakubnanista/7cc75df9a2b26277f443da8048fbbdf9 to your computer and use it in GitHub Desktop.
Save janjakubnanista/7cc75df9a2b26277f443da8048fbbdf9 to your computer and use it in GitHub Desktop.
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