Skip to content
Functionutilsv0.10.0

hasKeys

Checks that the specified nested keys exist on a possibly distributed union object and are not null or undefined, narrowing the object type to reflect those keys with their types from the original union.

hasKeys<Obj, Keys>(
    obj: Obj,
    keys: Keys[]
): obj is Obj &
    UnionToIntersection<
        Keys extends unknown
            ? PathToObj<
                  Keys,
                  UnionToIntersection<
                      NonNullable<DeepGet<Obj, Keys>>
                  >
              >
            : never
    >
interface Test {
  a?: {
    b?: {
      c?: string;
    };
  } | null;
  x?: number | null;
}

const obj: Test = { a: { b: { c: 'hello' } }, x: 42 };

if (hasKeys(obj, ['a.b.c', 'x'])) {
  // Here, obj is narrowed to:
  // {
  //   a: { b: { c: string } };
  //   x: number;
  // }
  console.log(obj.a.b.c.toUpperCase());
  console.log(obj.x.toFixed(2));
}

Obj

Obj

Keys

Keys

obj

obj: Obj

keys

keys: Keys[]

An array of dot-notation paths to check.