Sub topic 2
Equality Checks and Type Narrowing
Assume you know TypeScript union types, functions, and basic if and switch statements. Type narrowing is TypeScript’s control flow analysis: it uses checks in your code to replace a broad type with a more specific type inside a branch.
Equality checks and null/undefined handling
Equality checks can narrow values when TypeScript can determine which union members remain. A common pattern handles both null and undefined:
function greet(name: string | null | undefined): string {
if (name == null) {
return "Hello, stranger";
}
return `Hello, ${name.toUpperCase()}`;
}The == null check is intentional. It matches both null and undefined, so name is a string after the early return. Use === null when you want to check only null.
Narrowing with the `in` operator
The in operator checks whether a property exists. TypeScript uses that result to choose between object types:
type Fish = { swim(): void };
type Bird = { fly(): void };
function move(animal: Fish | Bird): void {
if ("swim" in animal) {
animal.swim();
} else {
animal.fly();
}
}The property should distinguish the union members. An optional property may exist on both sides, so it might not narrow as expected.
Narrowing with `instanceof`
Use instanceof when one branch contains class instances:
function messageOf(error: Error | string): string {
return error instanceof Error ? error.message : error;
}The true branch treats error as an Error; the false branch treats it as a string. This check depends on the runtime prototype, so it is mainly useful for classes created in the same JavaScript environment.
Discriminated unions
A discriminated union gives every variant a shared property with a different literal value. That property is called the discriminant.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
}
}Checking shape.kind narrows the object and exposes the correct fields.
Exhaustiveness checking with `never`
A never value cannot exist. Assigning the default case to never makes the compiler report an error when a new union member is not handled.
function areaChecked(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
default: {
const unreachable: never = shape;
return unreachable;
}
}
}Exercise
Why does name == null narrow string | null | undefined to string after the return?
Show answer
It matches both nullish values, and the return removes those possibilities from the remaining control-flow path.