Lesson 2 · Unit 08
Designing with types
Shape your types so that wrong states cannot be written down
What you practise
- States that cannot be wrong because the types forbid them,
as const, unions against enums, thenevercheck that every case is handled, type guards
Try a question from this lesson
Pick one
This value says a request is still loading, has its data, and has failed, all at once. Does the compiler object?
type Load = {
loading: boolean;
data?: string;
error?: string;
};
const r: Load = {
loading: true, data: "hi", error: "no",
};Correct answer
No: each property is allowed on its own
Why
The type allows every combination of its three properties, and most of those make no sense. The compiler can only forbid what the type forbids. The fix is not more care. It is a better type.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Only the states that exist
Instead of one shape with optional parts, write a union: one shape per real state, each with a state property that names it.
Now data without "done", or an error while loading, cannot even be written down. The nonsense combinations are not handled. They are gone.
type Load =
| { state: "loading" }
| { state: "done"; data: string }
| { state: "failed"; error: string };
const a: Load = { state: "loading" };
const b: Load = {
state: "done", data: "hi",
};Concept
The never tripwire
When every case has returned, no value is left. The compiler gives what remains the type never: "cannot happen".
Assigning it to a never variable sets a tripwire. Add a third colour to Light one day, and that line stops compiling until this function handles it.
type Light = "red" | "green";
function next(l: Light): Light {
if (l === "red") return "green";
if (l === "green") return "red";
const left: never = l;
return left;
}Concept
as const
The compiler widens: a value that could change later gets the general type, string, not the exact text.
as const says: this will never change, keep the exact values. Properties get literal types and become readonly. It is how plain data keeps up with literal unions.
let a = "left"; // type: string
const b = "left"; // type: "left"
const c = { dir: "left" };
// c.dir has type string
const d = { dir: "left" } as const;
// d.dir has type "left", and is readonly9 more exercises in the app
- 3× multiple choice
- 3× type the answer
- 1× true or false
- 1× fill the blanks
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.