utils.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. export type Nullable<T> = T | null
  2. // eslint-disable-next-line @typescript-eslint/no-empty-interface, @typescript-eslint/no-empty-object-type
  3. interface DeepReadonlyArray<T> extends ReadonlyArray<DeepReadonly<T>> {}
  4. type DeepReadonlyObject<T> = {
  5. readonly [P in keyof T]: DeepReadonly<T[P]>
  6. }
  7. export type DeepReadonly<T> = T extends (infer R)[]
  8. ? DeepReadonlyArray<R>
  9. : T extends (...args: any[]) => void
  10. ? T
  11. : T extends object
  12. ? DeepReadonlyObject<T>
  13. : T
  14. export type DeepPartial<T> = Partial<{ [P in keyof T]: DeepPartial<T[P]> }>
  15. export type MergeAndOverride<Parent, Own> = Own & Omit<Parent, keyof Own>
  16. export type Keys<T extends object> = (keyof T)[]
  17. /**
  18. * Helper to create type guards for literal unions
  19. *
  20. * @example
  21. * ```ts
  22. * const fruit = ['apple', 'banana', 'cherry'] as const;
  23. * type Fruit = typeof fruit[number];
  24. * const isFruit = mkLiteralUnionTypeguard(fruit);
  25. *
  26. * // Usage example:
  27. * function eatFood(food: unknown[]) {
  28. * food.forEach(item => {
  29. * if (isFruit(item)) {
  30. * eatFruit(item)
  31. * } else {
  32. * console.log(`Not fruit ${item}`)
  33. * }
  34. * })
  35. * }
  36. * eatFood(['banana', 'pizza'])
  37. * ```
  38. *
  39. * @param xs A readonly tuple of allowed values (strings, numbers, or symbols).
  40. * @returns A type guard function `(value: unknown) => value is T[number]`.
  41. */
  42. export function mkLiteralUnionTypeguard<
  43. const T extends readonly (string | number | symbol)[],
  44. >(xs: T) {
  45. return (v: unknown): v is T[number] =>
  46. (xs as readonly (string | number | symbol)[]).includes(v as any)
  47. }