Explain it simply
Explain it simply
In Set 1 you practised one concept at a time. In Set 2 every exercise combines two or three ideas from the intermediate and advanced lessons; the Shape exercise alone needs a union type, literal types and narrowing.
At this level more compiler errors are normal. A message like "Property 'radius' does not exist on type 'Shape'" is telling you exactly what is wrong. Read the warm-up, then before each exercise pause for a few seconds and ask which concepts it needs.
Problem → Why → Solution
The problem: reading a variant's field without narrowing
On a first attempt at exercise 1, everyone wants to read shape.radius right away. The compiler refuses: "Property 'radius' does not exist on type 'Shape'", because a Shape might be a square, and squares have no radius.
Silencing it with (shape as any).radius compiles. But pass a square and you get undefined ** 2, which is NaN. Nothing throws, so that NaN can travel quietly into a total or an invoice.
function getArea(shape: Shape): number {
return Math.PI * shape.radius ** 2;
// Error: Property 'radius' does not exist on type 'Shape'.
}
function getAreaSilenced(shape: Shape): number {
return Math.PI * (shape as any).radius ** 2; // a square gives NaN
}Why does the compiler refuse?
On a union you may only read properties that every variant has; here that is kind. Only after checking shape.kind === "circle" does TypeScript narrow shape to the circle variant and allow radius. The error is not a nuisance; it is telling you which case you have not checked yet.
The concepts behind the four exercises
The four exercises look different, but they all answer one question: how do you prove to the compiler what a value really is? Checking kind, admitting that a result may be undefined, declaring override and writing a predicate are all different forms of that proof.
Discriminated unions and never
When every variant has a literal property such as kind, switch (shape.kind) narrows shape to a single variant inside each case. Writing const unhandled: never = shape; in the default branch means that adding a triangle variant later is a compile error until you add its case.
A generic class that returns T | undefined
Stack<T> pushes, pops and peeks without knowing the item type. Because the stack can be empty, pop() and peek() must return T | undefined. Array.pop() already returns T | undefined, but this.items[this.items.length - 1] is typed as plain T under default settings, so write the T | undefined return type yourself.
Inheritance and override
class Dog extends Animal inherits every Animal method. override makeSound() replaces the parent's version, and the override keyword makes it an error if the parent has no method by that name, for example after a typo. With noImplicitOverride enabled the keyword is required. If a subclass writes a constructor, it must call super() before touching this.
Type predicates (value is string)
function isString(value: unknown): value is string promises the compiler that a true result means value is a string, so mixed.filter(isString) becomes string[]. Annotate the return type as boolean and the promise is gone; the result is unknown[]. Since TypeScript 5.5 the compiler can infer a predicate for simple functions with no return annotation, but writing : boolean switches that inference off.
| Exercise | Concept | Key syntax |
|---|---|---|
| 1. Shape | Narrowing | switch (shape.kind) |
| 2. Stack<T> | Generics | pop(): T | undefined |
| 3. Dog | Inheritance | override makeSound() |
| 4. isString | Type guard | value is string |
- Check kind before variant fields
- Can be empty? Return T | undefined
- Replacing a parent? Write override
- Wrap runtime checks in a predicate
All four exercises share one pattern: do a runtime check and write it in a form the compiler understands.
General pattern
switch (value.kind) {
case "a": return handleA(value); // value narrowed to the "a" variant
default: { const rest: never = value; throw new Error(String(rest)); }
}
class Box<T> { take(): T | undefined { /* may be empty */ } }
class Child extends Parent { override method(): R { /* ... */ } }
function isType(v: unknown): v is Type { return /* runtime check */; }Four shapes: a narrowing switch with a never check, a generic method that may return undefined, an overriding subclass, and a type predicate.
Solved warm-up: payments, a queue and notifiers
The four warm-ups use the same concepts as the exercises but different data: a Payment union, a Queue<T> (FIFO, the opposite of a stack), Notifier/EmailNotifier, and an isNumber guard. Notice that isNumber also rejects NaN, because typeof NaN is "number".
// Warm-up 1: a discriminated union, narrowed with switch
type Payment =
| { kind: "card"; amount: number; feePercent: number }
| { kind: "cash"; amount: number };
function totalCharge(p: Payment): number {
switch (p.kind) {
case "card":
return p.amount + (p.amount * p.feePercent) / 100;
case "cash":
return p.amount;
}
}
// Warm-up 2: a generic queue (first in, first out)
class Queue<T> {
private items: T[] = [];
enqueue(item: T): void {
this.items.push(item);
}
dequeue(): T | undefined {
return this.items.shift();
}
get size(): number {
return this.items.length;
}
}
// Warm-up 3: overriding a method in a subclass
class Notifier {
send(message: string): string {
return `Notice: ${message}`;
}
}
class EmailNotifier extends Notifier {
override send(message: string): string {
return `Email -> ${super.send(message)}`;
}
}
// Warm-up 4: a user-defined type guard
function isNumber(value: unknown): value is number {
return typeof value === "number" && !Number.isNaN(value);
}
console.log(totalCharge({ kind: "card", amount: 200, feePercent: 3 }));
const queue = new Queue<string>();
queue.enqueue("first");
queue.enqueue("second");
console.log(queue.dequeue(), queue.size);
const notifier: Notifier = new EmailNotifier();
console.log(notifier.send("build finished"));
const raw: unknown[] = [10, "11", 12, NaN];
console.log(raw.filter(isNumber));Code breakdown
- Narrowed per case
return p.amount + (p.amount * p.feePercent) / 100;Inside case "card", p is the card variant, so feePercent is available; in case "cash" it would be an error. 200 + 6 = 206.
- May be empty
dequeue(): T | undefined {shift() removes the front item and returns undefined on an empty queue. That is why "first" comes out and size is left at 1.
- Override and reuse the parent
override send(message: string): string {The variable is typed as Notifier, but the runtime object is an EmailNotifier, so the subclass method runs; super.send() reuses the parent's text.
- Type predicate
function isNumber(value: unknown): value is number {filter(isNumber) produces number[]. The string "11" and NaN are dropped, leaving [ 10, 12 ].
206
first 1
Email -> Notice: build finished
[ 10, 12 ]How to test your answers
- getArea(): radius 1 gives 3.14 (with toFixed(2)) and side 3 gives 9
- Stack<T>: after pushing 1, 2, 3, pop() returns 3 and peek() returns 2; peek() must not remove anything
- Dog: const pet: Animal = new Dog(); pet.makeSound() returns "Woof"
- isString: [1, "two", 3, "four"] becomes [ 'two', 'four' ] and its type is string[]
Check the types too
Hover over the strings variable in your editor. If it shows unknown[], isString's return type is not a predicate yet. The output can be right while the type is still wrong.
In real projects
In real projects
Discriminated unions are everywhere in app state and messages: Redux actions, request states like { status: "loading" } | { status: "success"; data } | { status: "error"; error }, and WebSocket message types all follow this pattern. The never check points out, at compile time, every place you forgot to handle when a new variant is added.
Stacks power undo/redo history, the browser's back button and bracket-matching parsers. Type guards are the main tool for checking unknown data from JSON.parse() or fetch(); for data with many fields, teams usually reach for a schema library such as zod instead of hand-written guards. Inheritance shows up most in framework classes, such as Error subclasses, while application code tends to prefer composition.
Common mistakes
Common mistakes
Annotating the guard as : boolean
function isString(value: unknown): boolean works correctly at runtime, but mixed.filter(isString) is still unknown[], so calling .toUpperCase() on the result is an error. Write value is string.
Calling pop() inside peek()
Writing peek() as return this.items.pop(); has the right type, but every peek() silently removes an item. peek() must only read this.items[this.items.length - 1].
Forgetting super() in a subclass constructor
Adding a constructor to Dog to store a name without calling super() gives "Constructors for derived classes must contain a 'super' call", and writing this.name before super() is also an error. Call super(...) first.
Silencing the union error with as any
(shape as any).radius makes the compile error go away, not the bug: a square silently returns NaN. Whenever you feel the urge to add an assertion, ask which check you are skipping, and write that check instead.
Best practices
Best practices
- Turn on noImplicitOverride in tsconfig so the compiler flags methods that replace a parent without saying override
- When a guard needs more than one check (NaN, for example), write it once and reuse it everywhere
- Every time you add a union variant, let the switches with never checks show you what to update
Mini challenge
Practice Set 2: the four exercises
Without looking at the warm-up, fill in the TODOs: 1 is the Shape area, 2 is Stack<T>, 3 is the Dog override and 4 is the isString type guard. As a bonus, add isEmpty() to Stack.
- getArea() narrows with switch (shape.kind) and has a never check in default
- Stack<T>'s pop() and peek() follow LIFO order and return T | undefined
- Dog uses the override keyword and makeSound() returns "Woof"
- isString returns value is string, so the filtered result is string[]
// Exercise 1
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
function getArea(shape: Shape): number {
// TODO: switch on shape.kind; add a never check in default
}
// Exercise 2
class Stack<T> {
private items: T[] = [];
// TODO: push(item: T): void
// TODO: pop(): T | undefined (last in, first out)
// TODO: peek(): T | undefined (read the top, do not remove it)
// TODO (bonus): isEmpty(): boolean
}
// Exercise 3
class Animal {
makeSound(): string {
return "...";
}
}
// TODO: class Dog extends Animal, overriding makeSound() to return "Woof"
// Exercise 4
// TODO: function isString(value: unknown): value is stringExpected: It prints 3.14, 9, 3 2 false, Woof and [ 'two', 'four' ], one per line.
Show hint
pop() can return this.items.pop() directly; peek() reads the last index. isString just returns typeof value === "string"; what matters is its return type.
Show solution
// Exercise 1
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
function getArea(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.side ** 2;
default: {
const unhandled: never = shape;
throw new Error(`Unknown shape: ${JSON.stringify(unhandled)}`);
}
}
}
// Exercise 2
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
peek(): T | undefined {
return this.items[this.items.length - 1];
}
isEmpty(): boolean {
return this.items.length === 0;
}
}
// Exercise 3
class Animal {
makeSound(): string {
return "...";
}
}
class Dog extends Animal {
override makeSound(): string {
return "Woof";
}
}
// Exercise 4
function isString(value: unknown): value is string {
return typeof value === "string";
}
console.log(getArea({ kind: "circle", radius: 1 }).toFixed(2));
console.log(getArea({ kind: "square", side: 3 }));
const stack = new Stack<number>();
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.pop(), stack.peek(), stack.isEmpty());
const pet: Animal = new Dog();
console.log(pet.makeSound());
const mixed: unknown[] = [1, "two", 3, "four"];
const strings: string[] = mixed.filter(isString);
console.log(strings);Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Read a variant's fields only after checking kind, and add a never check in default
- Generic methods that can come back empty return T | undefined
- Write override when replacing a parent method, and call super() first in a subclass constructor
- A type guard must return value is Type; a plain boolean gives no narrowing
TypeScript Handbook — TypeScript