Dev Helpers

TypeScript / Unknown input

Check a nullable input explicitly

Dev Helpers · July 28, 2025

An explicit null check preserves valid values that a broad truthiness check would reject. The remaining branch gains a narrower type.

Worked example

const samples: unknown[] = [null, "Ada", 12, { id: 1 }, [2, 3], true];
console.log(samples.map((v) => (v === null ? "null" : typeof v)));

Result

[ 'null', 'string', 'number', 'object', 'object', 'boolean' ]

Implementation notes

Narrowing must match the actual allowed inputs. A null-only check can leave undefined in the type if the source permits both.

Try it yourself

Compare null with zero and an empty string.

Open the TypeScript example →

Editorial date July 28, 2025 · Published December 6, 2026

Related articles

Reject fractional cent amounts

A numeric type cannot by itself guarantee whole cents. Validate integrality where money enters the typed part of the application.

Infer route names from a registry

A route registry can drive both lookup and allowed route names. Type the keys from the registry so a removed route cannot survive in a separate union.