Page 02
Typescript
Narrowing and Type Guards
Core idea TypeScript becomes much more useful when you narrow uncertain values before using them. Revision points typeof, in, and custom predicates all help narrowing. Unions stay...
Core idea
TypeScript becomes much more useful when you narrow uncertain values before using them.
Revision points
typeof,in, and custom predicates all help narrowing.- Unions stay ergonomic when the branches are modeled clearly.
- Good narrowing reduces non-null assertions.
type Result = { ok: true; data: string } | { ok: false; error: string };
function handle(result: Result) {
if (result.ok) {
return result.data.toUpperCase();
}
return result.error;
}
What to remember
Push uncertainty to the edges, then narrow aggressively.