Discriminated unions, type guards and review
We reach one of the most useful patterns in all of TypeScript: the discriminated union. It models data that can be in several different states, where each state has its own information. Think of a screen loading data: before starting there is nothing, while loading there is no data but there is progress, when finished there is data and if it fails there is an error message. With a single object with optional properties it would be easy to create impossible combinations, such as data and error at once. A discriminated union makes those combinations impossible to even write.
The discriminant property
The recipe is simple: each member of the union is an object with a common property, usually called type, kind or status, whose value is a different literal in each member. That property is the discriminant. When you check its value with an if or a switch, TypeScript automatically narrows the union to the matching member, and inside each branch you only see the properties that exist in that state. If you add a new member and forget to handle it, the exhaustiveness check with never warns you.
type LoadState =
| { status: 'idle' }
| { status: 'loading'; progress: number }
| { status: 'success'; data: string[] }
| { status: 'error'; message: string };
function assertNever(value: never): never {
throw new Error('Unhandled case: ' + JSON.stringify(value));
}
function render(state: LoadState): string {
switch (state.status) {
case 'idle':
return 'Press start';
case 'loading':
return 'Loading ' + state.progress + '%';
case 'success':
return 'Items: ' + state.data.join(', ');
case 'error':
return 'Error: ' + state.message;
default:
return assertNever(state);
}
}
console.log(render({ status: 'loading', progress: 40 }));
console.log(render({ status: 'success', data: ['a', 'b'] }));type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; side: number }
| { kind: 'rectangle'; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'square':
return shape.side ** 2;
case 'rectangle':
return shape.width * shape.height;
}
}
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
function parseNumber(text: string): Result<number> {
const n = Number(text);
return Number.isNaN(n) ? { ok: false, error: 'Not a number: ' + text } : { ok: true, value: n };
}
const r = parseNumber('42');
if (r.ok) {
console.log(r.value + 1);
} else {
console.log(r.error);
}
console.log(area({ kind: 'square', side: 3 }));Custom type guards
In week 2 you saw that narrowing does not work through a helper function returning boolean. The solution is a type predicate: a function whose return is written parameter is Type. When it returns true, the compiler narrows the argument to that type in the corresponding branch. It is the bridge between the unknown world (unknown) and typing: you check the shape at runtime and, in exchange, gain the type. Be careful: TypeScript trusts your predicate, so a badly written check introduces lies into the type system.
interface Fish {
swim: () => void;
}
interface Bird {
fly: () => void;
}
function isFish(animal: Fish | Bird): animal is Fish {
return 'swim' in animal;
}
function isStringArray(value: unknown): value is string[] {
return Array.isArray(value) && value.every((item) => typeof item === 'string');
}
const pet: Fish | Bird = { swim: () => console.log('splash') };
if (isFish(pet)) {
pet.swim();
}
const input: unknown = ['a', 'b'];
if (isStringArray(input)) {
console.log(input.map((s) => s.toUpperCase()));
}As a final practice for the week, think of the places in your programs where today you use several booleans or optional properties to describe a state: isLoading, hasError, data?. Almost always a discriminated union is better, because it eliminates impossible combinations, such as loading and having an error at once. This redesign is one of the most profitable changes you can make to existing code: it reduces bugs, simplifies checks and makes the compiler work in your favor every time someone adds a new state.
Проверьте себя
Вопрос 1 из 6What does Partial<T> do?
✎ Мои заметки
Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов