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.
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.
Mark this lesson complete
Signed in, your progress follows you to every device.