Skip to content

Instantly share code, notes, and snippets.

@gabrielmlinassi
Created February 22, 2023 14:48
Show Gist options
  • Save gabrielmlinassi/3df4599f6807bb43059a69a4db71b969 to your computer and use it in GitHub Desktop.
Save gabrielmlinassi/3df4599f6807bb43059a69a4db71b969 to your computer and use it in GitHub Desktop.
Example of Functional Programming composition funciton with TypeScript Generics
interface IMealCategory {
id: number
key: 'desert' | 'slow-cook' | 'breakfast' | 'protein'
}
const getMealCategoryBy = <T extends IMealCategory, K extends keyof IMealCategory>(mealCategories: T[], by: K) => {
return (value: T[K]) => {
return mealCategories.find((mealCategory) => {
return mealCategory[by] === value
})
}
}
const mealCategories: IMealCategory[] = [
{
id: 1,
key: 'desert'
},
{
id: 2,
key: 'breakfast'
},
{
id: 3,
key: 'protein'
}
]
const getMealCategoryByKey = getMealCategoryBy(mealCategories, 'key')
const getMealCategoryById = getMealCategoryBy(mealCategories, 'id')
console.log(getMealCategoryByKey('breakfast'))
console.log(getMealCategoryByKey('desert'))
console.log(getMealCategoryById(1))
console.log(getMealCategoryById(2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment