omit.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
  2. declare const File: any;
  3. /**
  4. * Type-safe omit function - returns a new object which omits the specified keys.
  5. */
  6. export function omit<T extends object, K extends keyof T>(obj: T, keysToOmit: K[]): Omit<T, K>;
  7. export function omit<T extends object | any[], K extends keyof T>(
  8. obj: T,
  9. keysToOmit: string[],
  10. recursive: boolean,
  11. ): T;
  12. export function omit<T, K extends keyof T>(obj: T, keysToOmit: string[], recursive: boolean = false): T {
  13. if ((recursive && !isObject(obj)) || isFileObject(obj)) {
  14. return obj;
  15. }
  16. if (recursive && Array.isArray(obj)) {
  17. return obj.map((item: any) => omit(item, keysToOmit, true)) as T;
  18. }
  19. return Object.keys(obj as object).reduce((output: any, key) => {
  20. if (keysToOmit.includes(key)) {
  21. return output;
  22. }
  23. if (recursive) {
  24. return { ...output, [key]: omit((obj as any)[key], keysToOmit, true) };
  25. }
  26. return { ...output, [key]: (obj as any)[key] };
  27. }, {} as Omit<T, K>);
  28. }
  29. function isObject(input: any): input is object {
  30. return typeof input === 'object' && input !== null;
  31. }
  32. /**
  33. * When running in the Node environment, there is no native File object.
  34. */
  35. function isFileObject(input: any): boolean {
  36. if (typeof File === 'undefined') {
  37. return false;
  38. } else {
  39. return input instanceof File;
  40. }
  41. }