Union types and type narrowing
Course contents (16 lessons)
- Getting started
- Why TypeScript? What it is and what it is not
- Setting up TypeScript: tsc and tsconfig.json
- Core types
- Basic types: primitives, arrays, tuples, any and unknown
- Typing functions: parameters, returns, optionals and overloads
- Objects, interfaces and type aliases
- Unions, literals and enums
- Union types and type narrowing
- Literal types, enums and as const
- Classes and generics
- Classes in TypeScript
- Generics: writing reusable typed code
- Built-in utility types: Partial, Pick, Omit, Record and more
- Advanced types
- Mapped and conditional types
- Modules, type imports and declaration files
- TypeScript in real projects
- Typing async code and API responses
- Strict mode and compiler flags that matter
- Migrating a JavaScript project to TypeScript
- Final project: a type-safe task manager
One of several types
Real data is often not one type. An id may be a string or a number. A function may return a result or null. A union type, written with |, says "this or that".
type ID = string | number;
let userId: ID = 42;
userId = "abc-123";
// userId = true; // Error: boolean is not part of ID
console.log(userId);
The catch: with a union, you can only use what is common to every member. If id is string | number, you cannot call id.toUpperCase(), because a number has no such method. First you have to find out which one you have. That step is called narrowing.
Narrowing with typeof
function formatId(id: string | number): string {
if (typeof id === "string") {
return id.toUpperCase(); // here id is string
}
return id.toFixed(0).padStart(6, "0"); // here id is number
}
console.log(formatId("ab-12")); // AB-12
console.log(formatId(42)); // 000042
Inside the if, TypeScript knows id is a string. After the if block returns, it also knows id must be a number. The compiler follows the flow of your code. This is why we write ordinary JavaScript checks and get types for free.
Truthiness and null checks
With strict mode, null and undefined are separate types, so a value that might be missing is a union:
function shout(text: string | null | undefined): string {
if (!text) {
return "(nothing)";
}
return text.toUpperCase(); // text is string here
}
function length(text?: string): number {
return text?.length ?? 0; // optional chaining and nullish coalescing
}
console.log(shout(null), shout("hi"), length(), length("abc"));
Careful: !text is also true for the empty string. If an empty string is a legal value, check text === null || text === undefined, or use text == null.
Narrowing with in and instanceof
interface Cat { meow(): string }
interface Dog { bark(): string }
function speak(pet: Cat | Dog): string {
if ("meow" in pet) {
return pet.meow();
}
return pet.bark();
}
function formatError(e: unknown): string {
if (e instanceof Error) {
return e.message;
}
return String(e);
}
console.log(speak({ meow: () => "meow" }), formatError(new Error("boom")));
in checks whether a property exists. instanceof checks the class. The second function is something you will write often. In catch (e) blocks the error is unknown under strict settings, since anything can be thrown in JavaScript.
Discriminated unions
This is the most useful pattern in the lesson. Give each member of the union a common property with a literal value, a "tag". Checking the tag narrows the whole object.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number }
| { kind: "rectangle"; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.side ** 2;
case "rectangle":
return shape.width * shape.height;
}
}
console.log(area({ kind: "circle", radius: 2 }).toFixed(2)); // 12.57
console.log(area({ kind: "rectangle", width: 3, height: 4 })); // 12
In each case, TypeScript knows exactly which variant it is dealing with, so shape.radius is allowed only in the circle branch. This pattern is excellent for state that has distinct modes, like a request that is loading, succeeded or failed, and it replaces a pile of optional properties.
Exhaustive checks
What if someone adds { kind: "triangle" } to Shape later? We want the compiler to tell us every switch that now misses a case. Add a final check using never:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
function assertNever(value: never): never {
throw new Error(`Unhandled case: ${JSON.stringify(value)}`);
}
function perimeter(shape: Shape): number {
switch (shape.kind) {
case "circle":
return 2 * Math.PI * shape.radius;
case "square":
return 4 * shape.side;
default:
return assertNever(shape);
}
}
console.log(perimeter({ kind: "square", side: 2 }));
If you add a new variant and forget to handle it, shape in the default branch is no longer never, and the compiler stops with an error right at that line. I consider this one of the best features of TypeScript.
Custom type guards
Sometimes the check is more complex than typeof. You can write a function whose return type is a type predicate, value is Type:
interface User {
id: number;
name: string;
}
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
typeof value.id === "number" &&
"name" in value &&
typeof value.name === "string"
);
}
const data: unknown = JSON.parse('{"id": 7, "name": "Ali"}');
if (isUser(data)) {
console.log(data.name.toUpperCase()); // data is User here
} else {
console.log("not a user");
}
The predicate is a promise that you make. If your function says value is User and the check is sloppy, TypeScript believes you anyway. So make the checks thorough. This is the right way to turn an unknown value, such as parsed JSON, into a typed one.
Unions of literals
A union of literal values is a lightweight alternative to enums. The next lesson covers it in detail:
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction): string {
return `Moving ${direction}`;
}
console.log(move("up"));
// move("diagonal"); // Error
Common mistakes
- Calling a member of only one type on the union. Narrow first.
- **Assuming
!valuemeans "missing".**0and""are also falsy. - **Using
aswhere a check would do.** A cast hides the problem, and a guard solves it. - Optional fields instead of a discriminated union. A type with
data?,error?andloading?allows impossible combinations. Use tagged variants. - Forgetting the exhaustive check. New variants then pass silently.
- Writing a sloppy type guard. A predicate that returns
truetoo easily gives you false safety.
Try it yourself
- Write
double(value: string | number)that doubles a number and repeats a string twice. - Create a discriminated union
Result = { ok: true; value: number } | { ok: false; error: string }and write a function that prints either. - Add a
trianglevariant toShapeand let the compiler show you where to update. - Write a type guard
isStringArray(value: unknown): value is string[].
function formatId(id: string | number): string {
if (typeof id === "string") {
return id.toUpperCase(); // here id is string
}
return id.toFixed(0).padStart(6, "0"); // here id is number
}
console.log(formatId("ab-12")); // AB-12
console.log(formatId(42)); // 000042
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account