Terminology (4)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Narrowing
- tsc treating a value as a smaller type after a check, on the path where the check passed.
- Discriminated union
- A union whose members share a literal property, such as kind, that tells them apart.
- Type guard
- A function returning x is T whose true result narrows x. Ordinary body/predicate type checks still apply; the declaration does not prove its runtime implication.
- Control flow analysis
- How tsc follows returns, branches and assignments to work out a value’s type at each point.
From a union to a usable value
Narrowing refines a value’s static type along a control-flow path. A check such as typeof, an equality test or a discriminant comparison removes possibilities from a union, making the remaining operations available in that branch.
TypeScript trusts the checks in the program. It adds no validation when the program runs. A user-written type predicate declares a classification promise; its implementation and the timing of later reads must support that promise.
01Checks the compiler reads
typeof "object" still includes null
A space-booking dashboard identifies spaces by ID. Its directory shows a floor or a reception fallback, its reservation view totals desk and room charges, and its occupancy feed may contain malformed records.
The dashboard location view can receive a structured room, a text label or no location. This reduced where probe asks what a broad runtime category check actually establishes before a field is read. Predict the checker’s result.
type Entry = { room: string } | string | null;
function where(entry: Entry): string {
if (typeof entry === "object") return entry.room;
return entry;
}
console.log(where({ room: "North" }), where("South"), where(null));
npx tsc --noEmit --strict --target ES2022 main.ts && node main.ts
Use the TypeScript setup from the first reading. This lesson follows the dashboard’s runtime checks and the types they establish.
02Type guards
tsc believes a guard, right or wrong
Reservation routing relies on a helper’s declared classification. This reduced calendar probe mixes meetings, days off and reminders; inspect which members the supplied test admits, then predict the loop’s lines.
type Meeting = { kind: "meeting"; room: string };
type DayOff = { kind: "dayOff" };
type Reminder = { kind: "reminder"; text: string };
type Entry = Meeting | DayOff | Reminder;
function isMeeting(entry: Entry): entry is Meeting {
return entry.kind !== "dayOff";
}
const entries: Entry[] = [
{ kind: "meeting", room: "North" },
{ kind: "dayOff" },
{ kind: "reminder", text: "call" }
];
for (const entry of entries) {
if (isMeeting(entry)) console.log(`book ${entry.room}`);
}
03Callbacks
A narrowing does not survive a later assignment
A deferred location update can run after the dashboard’s selected room changes. The callback below keeps one earlier value and also reads the mutable selection; follow that timing and predict its output.
let room: string | undefined = "North";
if (room !== undefined) {
const booked = room;
setTimeout(() => console.log(booked.toUpperCase(), room?.toUpperCase()), 0);
}
room = undefined;
04Repair the space-booking dashboard
Directory, reservation costs, then occupancy
The directory maps each space ID to a floor; ground floor 0 is a real destination. Reservations use the same IDs: desks cost 100 per day, while rooms cost 50 per day plus a setup fee. The occupancy view accepts desk and room readings, skips future device kinds and refuses malformed known records so an incomplete total is never displayed as trusted.
This lab is TypeScript-only. Each file contains its imports, reader and complete caller.
Repair the space-booking dashboard
A truthiness check, a guard that checks too little, then data from outside.
In the frontend Narrow a nullable location before displaying its room. Optional
A read-only location label receives a room object or null from its typed parent. The null branch determines which text appears and leaves the room field safe to read in the other branch.
type Place = { room: string } | null;
export default function LocationLabel({ place }: { place: Place }) {
if (place === null) return <p>No location selected</p>;
return <p>Room {place.room}</p>;
}
The early return removes null before place.room is read. This component needs no client state or event handler; the parent supplies the typed prop.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?