Created
February 22, 2023 14:48
-
-
Save DonHuskini/3df4599f6807bb43059a69a4db71b969 to your computer and use it in GitHub Desktop.
Example of Functional Programming composition funciton with TypeScript Generics
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
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