Sub topic 2
Narrowing: proving a value is present
Assume you know basic TypeScript types, union types, interfaces, and tsconfig.json. This chapter uses strictNullChecks, where null and undefined remain separate members of a union until your code proves otherwise.
Narrowing: proving a value is present
Narrowing is the compiler’s process of reducing a union type after a check. An equality check against null handles both missing values when written as == null:
function shout(value: string | null | undefined): string {
if (value == null) {
return "";
}
return value.toUpperCase(); // value is string here
}A truthiness check also narrows values, but it rejects every falsy value, including "", 0, and false. Use it only when those values should count as absent.
function label(value: string | undefined): string {
if (!value) {
return "unnamed";
}
return value.toUpperCase();
}A type guard is a condition that gives TypeScript more specific type information. Built-in checks such as typeof, instanceof, and !== undefined are common examples.
flowchart TD
A["string | null | undefined"] --> B{"value == null?"}
B -->|yes| C["Handle missing value"]
B -->|no| D["value is string"]Optional chaining with `?.`
Optional chaining reads a property or calls a method only when the value before ?. is not null or undefined. Otherwise, the whole expression produces undefined.
interface User {
name: string;
address?: { city?: string };
}
function cityOf(user: User): string {
return user.address?.city ?? "unknown";
}Here, address?.city avoids an exception when address is missing. Optional chaining does not make the result a string. Its result can still be undefined.
> callout note > Optional chaining handles access safely. It does not choose a useful fallback value.
Defaults with `??` and why it is not `||`
Nullish coalescing returns its left side unless that value is null or undefined. The || operator replaces every falsy value.
const retries = 0;
const withOr = retries || 3; // 3
const withNullish = retries ?? 3; // 0Use ?? when zero, an empty string, or false are valid values. Use || only when all falsy values should trigger the fallback.
Exercise
What does user.address?.city ?? "unknown" return when address is missing?
Show answer
It returns "unknown" because optional chaining produces undefined, and ?? replaces undefined.