Skip to content

Instantly share code, notes, and snippets.

@kctang
Created March 11, 2020 04:05
Show Gist options
  • Save kctang/5b63f5f6c7303b3c6cf2d65a956b9d6a to your computer and use it in GitHub Desktop.
Save kctang/5b63f5f6c7303b3c6cf2d65a956b9d6a to your computer and use it in GitHub Desktop.
// type from list of valid string values
type Category = 'action' | 'comedy' | 'drama'
// simple assignment (with IDE auto-complete)
const myCategory: Category = 'comedy'
const chooseCategory = () => {
// BAD: repeat the list of categories for selection
const categories = ['action', 'comedy', 'drama']
return categories[1]
}
// --- SOLUTION: DRY (don't repeat yourself)
const categories2 = <const>['action', 'comedy', 'drama']
type Category2 = typeof categories2[number]
// simple assignment (with IDE auto-complete)
const myCategory2: Category2 = 'comedy'
// GOOD: list of valid strings not repeated. used as both values and type definition
const chooseCategory2 = () => categories2[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment