Skip to content

assertNotNull

function assertNotNull<T>(value?, message?): T;

Defined in: assert-not-null.ts:37

Return value typed without null and undefined, or throw an AssertError when it is null or undefined.

Only null and undefined fail: other falsy values (0, "", false, NaN) are returned unchanged.

Type Parameter
T
Parameter Type Description
value? T | null The value to check.
message? string The AssertError message. Defaults to AssertError’s default, "unexpected null or undefined".

T

value, narrowed to T.

When value is null or undefined.

Narrow a nullable lookup

import { assertNotNull } from "@xtandard/lib";
const users = new Map([["ada", { name: "Ada" }]]);
const ada = assertNotNull(users.get("ada"), "user ada is missing");
ada.name; // "Ada" (ada: { name: string }, not ... | undefined)
assertNotNull(users.get("bob"), "user bob is missing");
// throws AssertError("user bob is missing")

Only null and undefined fail

assertNotNull(0); // 0
assertNotNull(""); // ""
assertNotNull(false); // false
assertNotNull(null); // throws AssertError("unexpected null or undefined")