pick.ts 959 B

12345678910111213141516171819202122232425
  1. /**
  2. * Returns a new object which is a subset 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 string>(props: T[]): <U>(input: U) => Pick<U, Extract<keyof U, T>>;
  7. export function pick<U, T extends keyof U>(input: U, props: T[]): { [K in T]: U[K] };
  8. export function pick<U, T extends keyof U>(
  9. inputOrProps: U | T[],
  10. maybeProps?: T[],
  11. ): { [K in T]: U[K] } | ((input: U) => Pick<U, Extract<keyof 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<U, T extends keyof U>(input: U, props: T[]): { [K in T]: U[K] } {
  19. const output: any = {};
  20. for (const prop of props) {
  21. output[prop] = input[prop];
  22. }
  23. return output;
  24. }