All files / src/types null.tsx

91.66% Statements 11/12
90.9% Branches 10/11
100% Functions 3/3
91.66% Lines 11/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50                      169x       169x 5x   2x       164x 38x   38x 145x         38x     126x                         149x    
type RecursivelyReplaceNullWithUndefined<T> = T extends null
  ? undefined
  : T extends (infer U)[]
  ? RecursivelyReplaceNullWithUndefined<U>[]
  : T extends object
  ? { [K in keyof T]: RecursivelyReplaceNullWithUndefined<T[K]> }
  : T;
 
export function nullsToUndefined<T>(
  value: T
): RecursivelyReplaceNullWithUndefined<T> {
  Iif (value === null) {
    return undefined as RecursivelyReplaceNullWithUndefined<T>;
  }
 
  if (Array.isArray(value)) {
    return value.map((v) =>
      // eslint-disable-next-line @typescript-eslint/no-unsafe-return
      nullsToUndefined(v)
    ) as RecursivelyReplaceNullWithUndefined<T>;
  }
 
  if (typeof value === "object" && value !== undefined) {
    const result: Record<PropertyKey, unknown> = {};
 
    for (const key in value) {
      result[key] = nullsToUndefined(
        (value as Record<PropertyKey, unknown>)[key]
      );
    }
 
    return result as RecursivelyReplaceNullWithUndefined<T>;
  }
 
  return value as RecursivelyReplaceNullWithUndefined<T>;
}
 
/**
 * True when `value` is a non-null, non-array object.
 *
 * Useful at an API boundary where the declared return type is a single
 * resource. A plain truthiness check is not enough there, because `[]` is
 * truthy: a caller that guards with `if (resource)` lets an array through and
 * then reads a field off it, producing "cannot read properties of undefined"
 * far from the cause.
 */
export function isPlainObject(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}