Last active
April 20, 2022 08:26
-
-
Save mskoroglu/4a77328fe6982df256be054d8d4a0235 to your computer and use it in GitHub Desktop.
TypeScript type-safe pick function
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
/** | |
* Usage | |
* ```ts | |
* const person = { name: "John", surname: "Doe", age: 35 }; | |
* console.log(pick(person, "surname", "age")); | |
* ``` | |
* | |
* Result | |
* ```json | |
* { surname: 'Doe', age: 35 } | |
* ``` | |
*/ | |
export default function pick<O, K extends keyof O>(obj: O, ...keys: K[]): Pick<O, K> { | |
return keys.reduce((acc, key) => ({ ...acc, [key]: obj[key] }), {} as any); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment