Boss lesson · Unit 08
A task manager
One program from an empty file: model, commands, storage, tests and a refactor
What you practise
- One program from an empty file: a typed data model, commands as a union, asynchronous saving and loading, tests, and a refactor the compiler guides. What to learn next
Try a question from this lesson
Pick one
An empty file, and a first decision: the model for one task. Does line 6 compile?
type Task = {
id: number;
title: string;
done: boolean;
};
const t: Task = { id: 1, title: "milk" };Correct answer
No: done is missing
Why
A type has no default values. done is required, so the compiler insists that every task in the program is complete. Had it been done?: boolean, every reader would have had to cope with undefined.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Commands are data
Everything the user can do becomes a value: a command, with a kind and exactly the data that kind needs.
The whole program is then one function that takes the list and a command and returns the new list. A finish command without an id does not compile, and neither does a kind nobody defined.
type Command =
| { kind: "add"; title: string }
| { kind: "finish"; id: number }
| { kind: "remove"; id: number };
const first: Command = {
kind: "add", title: "milk",
};Concept
Saving and loading
Real storage is slow, so saving and loading are async. Here a variable stands in for the file, and wait for the delay.
Loading is the boundary from the inventory boss: parse, then check before trusting. toTasks keeps only the entries that really are tasks.
let disk = "[]"; // stands in for a file
async function save(tasks: Task[]) {
await wait(5);
disk = JSON.stringify(tasks);
}
async function load(): Promise<Task[]> {
await wait(5);
return toTasks(JSON.parse(disk));
}Concept
What to learn next
You started with one console.log. You now model data with types, check it at the boundary, handle failure, and write asynchronous code that a compiler has read first.
Two good next steps. TypeScript in Depth takes the type system much further: types that compute other types. React builds user interfaces with exactly the TypeScript you now know.
9 more exercises in the app
- 3× fill the blanks
- 3× type the answer
- 1× order the lines
- 2× multiple choice
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.