Created
March 22, 2020 11:23
-
-
Save aapzu/cfbcbd78f55ec7a1a44237826af9c3c7 to your computer and use it in GitHub Desktop.
Type safe pick function
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
import pick, { pickAndGetRest } from "./pick" | |
describe("pick util", () => { | |
it("picks from an object", () => { | |
const obj = { | |
a: 1, | |
b: 2, | |
c: 3, | |
foo: "bar", | |
bar: "bah", | |
} | |
const picked = pick(obj, "a", "c", "bar") | |
expect(picked).toEqual({ | |
a: 1, | |
c: 3, | |
bar: "bah", | |
}) | |
}) | |
it("picks and gives the rest from an object", () => { | |
const obj = { | |
a: 1, | |
b: 2, | |
c: 3, | |
foo: "bar", | |
bar: "bah", | |
} | |
const [picked, rest] = pickAndGetRest(obj, "a", "c", "bar") | |
expect(picked).toEqual({ | |
a: 1, | |
c: 3, | |
bar: "bah", | |
}) | |
expect(rest).toEqual({ | |
b: 2, | |
foo: "bar", | |
}) | |
}) | |
}) |
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
export const pick = <T extends {}>(obj: T, ...keys: (keyof T)[]) => { | |
return pickAndGetRest(obj, ...keys)[0] | |
} | |
export const pickAndGetRest = <T extends {}, K extends keyof T>(obj: T, ...keys: K[]): [Pick<T, K>, Omit<T, K>] => { | |
const picked: any = {} | |
const rest: any = {} | |
for (let key of Object.keys(obj)) { | |
if (keys.includes(key as K)) { | |
picked[key] = obj[key] | |
} else { | |
rest[key] = obj[key] | |
} | |
} | |
return [picked, rest] | |
} | |
export default pick |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment