TypeScript for real code · Chapter 16 of 36
Boxes and results
By the end of this chapter you can write types, interfaces and classes that take a type parameter, so a box says on the outside what it holds. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Generics
- 4 tasks
- TypeScript
- In the all labs plan
The first 2 chapters of TypeScript for real code are free. This one comes with the all labs plan.
Why you need this
Anjali's new menu screen shows a blank list. The API answered, but the code read reply.data.itmes, and nothing complained, because Bunty typed every reply's data as any. The menu pages, the kitchen's undo stack and the order parser have the same problem: the code around them changes with what is inside, and every one of them says any.
The generic functions from the last two chapters do not cover this: the type that needs a parameter here is the box itself. Without one, you write a box type per thing it can hold, or any, which checks nothing:
type Saved = { savedAt: number; value: any };
const lastMenu: Saved = { savedAt: 1700, value: { items: ['masala chai'] } };
console.log(lastMenu.value.itmes.length);
$ typecheck demo.ts
No type errors.
$ node demo.ts
file:///workspace/chapters/16-generic-types/demo.ts:4
console.log(lastMenu.value.itmes.length);
^
TypeError: Cannot read properties of undefined (reading 'length')What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
ApiResponse: a reply that says what data it carries
Every API reply is { status, data }. Give ApiResponse a type parameter T for the type of data, with a default of unknown: ApiResponse<string> has data of type string (so data: 40 is a type error there), a plain ApiResponse has data of type unknown, not any, and status is a number whatever T is.
Then make menuResponse return an ApiResponse of menu items, so its data has the type MenuItem[]. menuResponse(MENU) is still { status: 200, data: MENU }.
- Task 2
paginate: a Page of whatever the list holds
paginate(list, page, size) returns one page of any list: paginate(MENU, 1, 2) has the items masala-chai and cutting-chai, page 1 and totalPages 2, and paginate([1, 2, 3], 2, 2) has the items [3]. The body already works.
Make the interface Page<T>, with items: T[] (page and totalPages stay numbers), so a Page<MenuItem> holding the number 40 is a type error. Make paginate generic, taking a T[] and returning a Page<T>: a page of menu items holds menu items, not any, and paginate([40, 25, 35], 1, 2).items is a list of numbers, not strings.
- Task 3
Stack: an undo stack with honest return types
The kitchen's undo stack. Make the class Stack<T>: the private list holds T, push takes a T, pop and peek return T | undefined (the stack may be empty), and size stays a number. On a new Stack<string>, pop() is undefined; after pushing 'masala chai x2' and 'bun maska x1', size is 2, peek() is 'bun maska x1', and pop() gives 'bun maska x1' then 'masala chai x2'.
So a Stack<string> refuses push(40), and const top: string = tickets.pop() is a type error. Write T | undefined on peek yourself: it reads by index, and that type says only T.
- Task 4 · interview question
Interview: Result, with ok and err that fit any Result
A Result is either { ok: true, value } or { ok: false, error }. Make it Result<T, E>, with E defaulting to string, so narrowing on ok works: once r.ok is true, r.value is a T and r.error cannot be read; once it is false, r.error is an E.
ok(value) and err(error) build the two cases: ok(40) is { ok: true, value: 40 } and err('no milk') is { ok: false, error: 'no milk' }. ok(40) must fit a Result<number, string> and ok(2) a Result<number, 404>, but ok(40) is not a Result<string>. err('no milk') must fit a Result<number, string> and err(404) a Result<string, 404>, but err('no milk') is not a Result<number, 404>.
parseQty returns a Result<number> (its errors are strings): parseQty('2') is ok(2), parseQty('two') is err('not a quantity: two'), and parseQty('0') is not ok. Dev will ask how ok can fit a Result whatever its error type is.
What you will learn
- Generic types and interfaces: Cached<T>, one box written once, filled in each time you use it, with a default when you do not.
- Generic classes: a class whose methods all agree on one T, chosen for each instance.
- never in a type argument: the type with no values, which fits into every other type.
More in Generics
Build "Boxes and results" yourself
Tapri’s codebase grows, and types keep it honest. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of TypeScript for real code are free. This one comes with the all labs plan.