Created
March 11, 2020 04:05
-
-
Save kctang/5b63f5f6c7303b3c6cf2d65a956b9d6a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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