Function assertProps

Asserts that an object has the specified properties with the specified types. Ideal for quick runtime type checking of API responses if you don't need a full schema validation.

const validated = assertProps(obj, { id: "string", age: "number" });
// obj is runtime validated and type is now narrowed down to { id: string; age: number }
// if the assertion fails, an error is thrown
console.log(obj.id, obj.age);
  • Type Parameters

    • T extends Record<string, "string" | "number" | "boolean">

    Parameters

    • obj: unknown
    • schema: T

    Returns asserts obj is {
        [K in string | number | symbol]: T[K] extends "string"
            ? string
            : T[K] extends "number"
                ? number
                : T[K] extends "boolean" ? boolean : never
    }