pick.ts 971 B

12345678910111213141516171819202122232425
  1. /**
  2. * Returns a new object which is a subject of the input, including only the specified properties.
  3. * Can be called with a single argument (array of props to pick), in which case it returns a partially
  4. * applied pick function.
  5. */
  6. export function pick<T extends object, U extends T = any>(props: Array<keyof T>): (input: U) => T;
  7. export function pick<T extends object, U extends T = any>(input: U, props: Array<keyof T>): T;
  8. export function pick<T extends object, U extends T = any>(
  9. inputOrProps: U | Array<keyof T>,
  10. maybeProps?: Array<keyof T>,
  11. ): T | ((input: U) => T) {
  12. if (Array.isArray(inputOrProps)) {
  13. return (input: U) => _pick(input, inputOrProps);
  14. } else {
  15. return _pick(inputOrProps, maybeProps || []);
  16. }
  17. }
  18. function _pick<T extends object, U extends T = any>(input: U, props: Array<keyof T>): T {
  19. const output: any = {};
  20. for (const prop of props) {
  21. output[prop] = input[prop];
  22. }
  23. return output;
  24. }