Skip to content

Instantly share code, notes, and snippets.

@supermacro
Created April 9, 2019 15:47
Show Gist options
  • Save supermacro/b6464ce192fa298b2329090669a0c57b to your computer and use it in GitHub Desktop.
Save supermacro/b6464ce192fa298b2329090669a0c57b to your computer and use it in GitHub Desktop.
TypeSafe `pick` and `omit` from lodash
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