Boss lesson · Unit 01
Unions and narrowing
Model a request so that impossible states cannot be written
What you practise
typeof,inand equality narrowing, a discriminated union for request states, the exhaustiveswitchthat fails to compile when a case is added
Try a question from this lesson
Pick one
A request is loading, done or failed. Each field here is independently on or off. How many combinations can the type hold, and how many are real?
interface Req {
loading: boolean;
data?: string[];
error?: string;
}Hint
Three yes/no facts: loading or not, data or not, error or not.
Correct answer
8 allowed, 3 real
Why
2 × 2 × 2 = 8 combinations type-check, including "loading, with data and an error". Only 3 mean anything. Every function that takes this type has to wonder about the other 5. A union lets you write down exactly the 3.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Unions and narrowing
A | B is a value that is an A or a B. Until you know which, you may only use what both have.
A check the compiler understands, like typeof, narrows the type inside the branch. After a return, the rest of the function knows the check failed.
function show(id: number | string) {
// id.toFixed(1) here: rejected
if (typeof id === "number") {
return id.toFixed(1); // number
}
return id.toUpperCase(); // string
}Concept
Discriminated unions
Give every case a property with a different literal type: a tag. Checking the tag tells the compiler which case it holds, and so which other fields exist.
This is the request from before with only its 3 real states. "Loading with an error" can no longer be written.
type Req =
| { kind: "loading" }
| { kind: "ok"; data: string[] }
| { kind: "error"; message: string };Concept
never: nothing is left
When every case has been ruled out, the value's type is never, the type with no values.
Assign what is left to a never in the default branch. Today it compiles. The day someone adds a fourth case, that line stops compiling and points at the switch that forgot it. Python's assert_never does the same for a type checker.
type Light = "red" | "green";
function go(l: Light): boolean {
switch (l) {
case "red": return false;
case "green": return true;
default:
const left: never = l;
return left;
}
}9 more exercises in the app
- 2× fill the blanks
- 3× multiple choice
- 2× type the answer
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.