Created
August 25, 2021 14:21
-
-
Save alii/7d5d8252ffb24f4b1551a6368afceffa to your computer and use it in GitHub Desktop.
Pick a subset of keys from an object in a type-safe fashion
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
/** | |
* Pick a subset of keys from an object in a type-safe fashion | |
* @param obj | |
* @param keys | |
*/ | |
export function pick<T, K extends Array<keyof T>>( | |
obj: T, | |
keys: K | |
): Pick<T, K[number]> { | |
return Object.fromEntries( | |
keys.filter(key => key in obj).map(key => [key, obj[key]]) | |
) as Pick<T, K[number]>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment