shelving/util/nullmodule

Type guards, assertions, and utility types for null and nullish (null | undefined) values. Use these instead of inline === null checks to get proper TypeScript type narrowing and consistent error messages.

Usage

ts
import {
  isNull, notNull, assertNull, assertNotNull, requireNotNull,
  isNullish, notNullish, assertNullish, assertNotNullish, requireNotNullish,
  getNull, type Nullable, type Nullish,
} from "shelving/util";

// Null checks.
isNull(null);            // true
notNull(null);           // false
requireNotNull(null);    // throws RequiredError
requireNotNull("hi");    // "hi"

// Nullish checks (null or undefined).
isNullish(undefined);    // true
isNullish(0);            // false
notNullish(0);           // true
requireNotNullish(null); // throws RequiredError

// Filter null values from an array using notNull as a type-guard predicate.
const values: Array<string | null> = ["a", null, "b"];
values.filter(notNull); // string[]

// getNull is useful as a no-op factory.
const fallback = getNull; // () => null

Functions

Go

getNull()function

Function that always returns null.

getNull(): null
Go

isNull()function

Is a value null?

isNull(value: unknown): value is null
Go

assertNull()function

Assert that a value is null.

assertNull(value: Nullable<T>, caller: AnyCaller = assertNull): asserts value is T
Go

notNull()function

Is a value not null?

notNull(value: Nullable<T>): value is T
Go

assertNotNull()function

Assert that a value is not null.

assertNotNull(value: Nullable<T>, caller: AnyCaller = assertNotNull): asserts value is T
Go

requireNotNull()function

Get the not-null version of a value, or throw RequiredError if it is null.

requireNotNull(value: Nullable<T>, caller: AnyCaller = requireNotNull): T
Go

isNullish()function

Is a value nullish (null or undefined)?

isNullish(value: Nullish<T>): value is null | undefined
Go

assertNullish()function

Assert that a value is nullish (null or undefined).

assertNullish(value: Nullish<T>, caller: AnyCaller = assertNullish): asserts value is T
Go

notNullish()function

Is a value not nullish (not null and not undefined)?

notNullish(value: Nullish<T>): value is T
Go

assertNotNullish()function

Assert that a value is not nullish (not null and not undefined).

assertNotNullish(value: Nullish<T>, caller: AnyCaller = assertNotNullish): asserts value is T
Go

requireNotNullish()function

Get the not-nullish version of a value, or throw RequiredError if it is null or undefined.

requireNotNullish(value: Nullish<T>, caller: AnyCaller = requireNotNullish): T

Types

Go

Nullabletype

Nullable is the value or null.

T | null
Go

Nullishtype

Nullish is the value or null or undefined.

T | null | undefined