object.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { pipe } from "fp-ts/function"
  2. import cloneDeep from "lodash/cloneDeep"
  3. import isEqual from "lodash/isEqual"
  4. export const objRemoveKey =
  5. <T, K extends keyof T>(key: K) =>
  6. (obj: T): Omit<T, K> =>
  7. pipe(cloneDeep(obj), (e) => {
  8. delete e[key]
  9. return e
  10. })
  11. export const objFieldMatches =
  12. <T, K extends keyof T, V extends T[K]>(
  13. fieldName: K,
  14. matches: ReadonlyArray<V>
  15. ) =>
  16. // eslint-disable-next-line no-unused-vars
  17. (obj: T): obj is T & { [_ in K]: V } =>
  18. matches.findIndex((x) => isEqual(obj[fieldName], x)) !== -1
  19. type JSPrimitive =
  20. | "undefined"
  21. | "object"
  22. | "boolean"
  23. | "number"
  24. | "bigint"
  25. | "string"
  26. | "symbol"
  27. | "function"
  28. type TypeFromPrimitive<P extends JSPrimitive | undefined> =
  29. P extends "undefined"
  30. ? undefined
  31. : P extends "object"
  32. ? object | null // typeof null === "object"
  33. : P extends "boolean"
  34. ? boolean
  35. : P extends "number"
  36. ? number
  37. : P extends "bigint"
  38. ? BigInt
  39. : P extends "string"
  40. ? string
  41. : P extends "symbol"
  42. ? Symbol
  43. : P extends "function"
  44. ? Function
  45. : unknown
  46. type TypeFromPrimitiveArray<P extends JSPrimitive | undefined> =
  47. P extends "undefined"
  48. ? undefined
  49. : P extends "object"
  50. ? object[] | null
  51. : P extends "boolean"
  52. ? boolean[]
  53. : P extends "number"
  54. ? number[]
  55. : P extends "bigint"
  56. ? BigInt[]
  57. : P extends "string"
  58. ? string[]
  59. : P extends "symbol"
  60. ? Symbol[]
  61. : P extends "function"
  62. ? Function[]
  63. : unknown[]
  64. export const objHasProperty =
  65. <O extends object, K extends string, P extends JSPrimitive | undefined>(
  66. prop: K,
  67. type?: P
  68. ) =>
  69. // eslint-disable-next-line
  70. (obj: O): obj is O & { [_ in K]: TypeFromPrimitive<P> } =>
  71. // eslint-disable-next-line
  72. prop in obj && (type === undefined || typeof (obj as any)[prop] === type)
  73. export const objHasArrayProperty =
  74. <O extends object, K extends string, P extends JSPrimitive>(
  75. prop: K,
  76. type: P
  77. ) =>
  78. // eslint-disable-next-line
  79. (obj: O): obj is O & { [_ in K]: TypeFromPrimitiveArray<P> } =>
  80. prop in obj &&
  81. Array.isArray((obj as any)[prop]) &&
  82. (obj as any)[prop].every(
  83. (val: unknown) => typeof val === type // eslint-disable-line
  84. )