find.d.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import type { Path } from './types';
  2. export interface Reference {
  3. /** Target value where pointer is pointing. */
  4. readonly val: unknown;
  5. /** Object which contains the target value. */
  6. readonly obj?: unknown | object | unknown[];
  7. /** Key which targets the target value in the object. */
  8. readonly key?: string | number;
  9. }
  10. /**
  11. * Finds a target in document specified by JSON Pointer. Also returns the
  12. * object containing the target and key used to reference that object.
  13. *
  14. * Throws Error('NOT_FOUND') if pointer does not result into a value in the middle
  15. * of the path. If the last element of the path does not result into a value, the
  16. * lookup succeeds with `val` set to `undefined`. It can be used to discriminate
  17. * missing values, because `undefined` is not a valid JSON value.
  18. *
  19. * If last element in array is targeted using "-", e.g. "/arr/-", use
  20. * `isArrayEnd` to verify that:
  21. *
  22. * ```js
  23. * const ref = find({arr: [1, 2, 3], ['arr', '-']});
  24. * if (isArrayReference(ref)) {
  25. * if (isArrayEnd(ref)) {
  26. * // ...
  27. * }
  28. * }
  29. * ```
  30. *
  31. * @param skipLast Number of steps to skip at the end. Useful to find reference of
  32. * parent step, without constructing a new `Path` array.
  33. */
  34. export declare const find: (val: unknown, path: Path) => Reference;
  35. export interface ArrayReference<T = unknown> {
  36. /** `undefined` in case JSON Pointer points to last element, e.g. "/foo/-". */
  37. readonly val: undefined | T;
  38. readonly obj: T[];
  39. readonly key: number;
  40. }
  41. export declare const isArrayReference: <T = unknown>(ref: Reference) => ref is ArrayReference<T>;
  42. export declare const isArrayEnd: (ref: ArrayReference) => boolean;
  43. export interface ObjectReference<T = unknown> {
  44. readonly val: T;
  45. readonly obj: Record<string, T>;
  46. readonly key: string;
  47. }
  48. export declare const isObjectReference: <T = unknown>(ref: Reference) => ref is ObjectReference<T>;