Type Guards

Take it as unknown, check it, and let a guard tell the compiler what you proved.

A type predicate, written value is Book as the return type, turns an ordinary boolean function into something that narrows. The compiler trusts it exactly as much as it trusts an as, so it is your job to make it honest.

Try it

Fix the data so it matches and watch it take the other branch.

loading editor…

checking…

Same bad data as the previous lesson. This time it takes the else branch, and nothing explodes. The one `as` inside the guard is contained: it is how you inspect an unknown object, and every field is still checked after it.

Check once, at the edge. Validate the API response, the form submission, the parsed file, the URL parameter. Behind that boundary, trust the types completely: that is what you paid for.

Defensive checks scattered through code that is already typed are a sign the boundary is in the wrong place.

For anything beyond a couple of fields, a schema validation library is worth it. Hand-written predicates get long, and a predicate with a mistake in it is exactly as dangerous as an as.

◈ Graded Types

Define a type Book with title (string) and year (number). Write a type guard called isBook(v: unknown): v is Book that returns true only when v is an object, is not null, has a title that is a string, and has a year that is a number. Then write parseBook(v: unknown): Book | null returning the value when it is a Book and null otherwise. No assertions on the result, and no any.

Checked against the compiler, not against how you wrote it. 3 visible and 5 hidden checks.

loading editor…
real tsc, strict mode

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back