Function hasKeys

  • Checks if an object has all of the provided own properties.

    Type Parameters

    • T extends object

    • K extends string | number | symbol

    • U extends readonly K[]

    Parameters

    • obj: T

      The object to check.

    • keys: U

      The properties to check for.

    Returns obj is T extends {
            [P in string | number | symbol]: unknown
        }
        ? T
        : never

    true if the check passes, false otherwise.

    Example

    Basic Usage

    hasKeys({ a: 1, b: 2, c: 3 }, ['a', 'b']) // true
    hasKeys({ foo: 1, bar: 2 }, ['buzz']) // false

    Type narrowing

    const obj: { a: string; b: string } | { c: number; d: number }

    if (hasKeys(obj, ['a'])) {
    obj // type: { a: string; b: string; }
    obj.c // error
    } else {
    obj // type: { c: number; d: number; }
    obj.a // error
    }

    Paired with assert

    import { assert } from 'uft'

    const obj: { a: string; b: string } | { c: number; d: number }
    assert(hasKeys(obj, ['d']), 'expected object to have key "d"')
    obj // type: { c: number; d: number }
  • Type Parameters

    • T extends object

    Parameters

    • obj: T
    • keys: PropertyKey[]

    Returns boolean

Generated using TypeDoc