Sub topic 5
Narrowing: proving a value is present
This chapter assumes you know basic TypeScript types, union types, interfaces, and tsconfig.json. It also assumes strictNullChecks is enabled. With this option, TypeScript treats null and undefined as real parts of a type. Before using a value, your code must prove that the value is present.
A nullable value is a union such as string | null:
function shout(name: string | null): string {
if (name === null) {
return "NO NAME";
}
return name.toUpperCase();
}
console.log(shout("Ada"));
console.log(shout(null));Inside the if block, name is null. After the early return, TypeScript narrows name to string, so calling toUpperCase() is safe.
Equality checks
Use === null or === undefined when you need to distinguish the two missing-value states.
function describe(value: string | null | undefined): string {
if (value === null) {
return "explicitly empty";
}
if (value === undefined) {
return "not provided";
}
return `text: ${value}`;
}
console.log(describe(null));
console.log(describe(undefined));
console.log(describe("ready"));When both null and undefined should have the same meaning, value == null is a useful exception to the usual rule of preferring strict equality. This check is true only for null and undefined.
function shoutIfPresent(value: string | null | undefined): string {
if (value == null) {
return "";
}
return value.toUpperCase();
}After the check, TypeScript knows that value is a string.
Truthiness checks
A truthiness check narrows away null and undefined:
function printLabel(label: string | null | undefined): void {
if (label) {
console.log(label.toUpperCase());
}
}However, truthiness also rejects valid values such as "", 0, and false. Use it only when every falsy value should count as absent.
function showRetries(retries: number | null): string {
if (retries === null) {
return "not configured";
}
return `${retries} retries`;
}
console.log(showRetries(0));The explicit === null check preserves the meaningful value 0.
`typeof` and user-defined guards
typeof can narrow primitive unions:
function format(input: string | number | null): string {
if (input === null) {
return "missing";
}
if (typeof input === "string") {
return input.toUpperCase();
}
return input.toFixed(2);
}For repeated checks, write a user-defined type guard. A type guard is a function whose return type tells TypeScript what is true when it returns true.
function isString(value: unknown): value is string {
return typeof value === "string";
}
const values: unknown[] = ["Ada", 42, null];
const names: string[] = values.filter(isString);
console.log(names);The value is string part lets TypeScript infer that names contains only strings. A guard must match its runtime test. An incorrect guard can hide errors from the compiler.
A practical narrowing pattern
At boundaries such as configuration, user input, or network responses, narrow immediately before passing data deeper into your program:
function requireName(name: string | null | undefined): string {
if (name == null || name.trim() === "") {
throw new Error("A non-empty name is required");
}
return name;
}
console.log(requireName("Ada"));This keeps the rest of the function working with the simpler type string.
Exercise
Why does if (count) make count unusable as a guaranteed nonzero number, even when its type is number | null?
Show answer
The truthiness check removes null, but it also treats 0 as false. Use count !== null when zero is a valid value.