Created
February 20, 2023 08:54
-
-
Save reinhrst/ae00182995771206ab76ad6dc613933f to your computer and use it in GitHub Desktop.
Typescript object pick and omit functions
This file contains 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
// typescript versions of https://stackoverflow.com/a/56592365/1207489 | |
const pick = <T extends {}, K extends keyof T>(obj: T, ...keys: K[]) => ( | |
Object.fromEntries( | |
keys | |
.filter(key => key in obj) | |
.map(key => [key, obj[key]]) | |
) as Pick<T, K> | |
); | |
const inclusivePick = <T extends {}, K extends (string | number | symbol)>( | |
obj: T, ...keys: K[] | |
) => ( | |
Object.fromEntries( | |
keys | |
.map(key => [key, obj[key as unknown as keyof T]]) | |
) as {[key in K]: key extends keyof T ? T[key] : undefined} | |
) | |
const omit = <T extends {}, K extends keyof T>( | |
obj: T, ...keys: K[] | |
) =>( | |
Object.fromEntries( | |
Object.entries(obj) | |
.filter(([key]) => !keys.includes(key as K)) | |
) as Omit<T, K> | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment