Sub topic 3
Narrowing unions with control flow
This chapter assumes you know basic JavaScript, can run tsc or use a TypeScript-aware editor, and have read the earlier chapters on primitives, inference, and union types.
Narrowing unions with control flow
TypeScript follows your if, switch, and return statements. After each check, it narrows the variable to the union members that are still possible.
function describe(value: string | number | null): string {
if (value === null) {
return "none";
}
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}any versus unknown
any turns off checking, so every operation on it compiles. unknown accepts any value, but you have to narrow it before you can use it. Use unknown for parsed JSON and other input from outside your code.
const raw: unknown = JSON.parse("42");
if (typeof raw === "number") {
console.log(raw.toFixed(2));
}void and never
void means a function returns no useful value. never means no value can exist at that point. If you assign the leftover value to never, the compiler reports an error when someone adds a new union member without a matching case.
type Shape = "circle" | "square";
function area(shape: Shape): number {
switch (shape) {
case "circle":
return 3.14;
case "square":
return 1;
default: {
const unreachable: never = shape;
return unreachable;
}
}
}Contextual typing for callbacks
When you pass a callback, its parameter types come from the place it is passed to. In [1, 2, 3].map((n) => n * 2), n is a number without any annotation.
Type assertions and their risks
value as Type tells the compiler to trust you. Nothing is checked at runtime, so a wrong assertion leads to a crash later in the program. Prefer narrowing whenever it is possible.
Preserving literals with as const and satisfies
as const makes properties readonly and keeps literal types. satisfies checks a value against a type but keeps the narrower type TypeScript inferred.
const config = { port: 8080, mode: "dev" } as const;
type Palette = Record<string, string | number[]>;
const colors = {
red: [255, 0, 0],
green: "#00ff00",
} satisfies Palette;
colors.red.map((channel) => channel / 255);If you wrote const colors: Palette instead, colors.red would have the type string | number[], and the map call would fail to compile.
Exercise
Why is unknown safer than any for the result of JSON.parse?
Show answer
TypeScript rejects operations on an unknown value until you narrow it, for example with typeof. With any, every operation compiles, so mistakes only appear at runtime.
Exercise
What does satisfies give you that a type annotation does not?
Show answer
It checks the value against the type and still keeps the more precise inferred type, such as number[] for colors.red.