Created
April 9, 2019 15:47
-
-
Save supermacro/b6464ce192fa298b2329090669a0c57b to your computer and use it in GitHub Desktop.
TypeSafe `pick` and `omit` from lodash
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
const pickFunc = <T extends {}, K extends keyof T>( | |
obj: T, | |
predicate: (k: string) => boolean | |
): Pick<T, K> => | |
Object | |
.keys(obj) | |
.filter(predicate) | |
.reduce((filteredObj: Pick<T, K>, key) => ({ | |
...filteredObj, | |
[key]: obj[key as keyof T] | |
}), {} as Pick<T, K>) | |
// filters an object based on an array of keys | |
const pick = <T extends {}, K extends keyof T>(obj: T, keys: Array<K>): Pick<T, K> => | |
pickFunc( | |
obj, | |
k => keys.includes(k as K) | |
) | |
const omit = <T extends {}, K extends keyof T>(obj: T, keys: Array<K>): Pick<T, K> => | |
pickFunc( | |
obj, | |
k => !keys.includes(k as K) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment