Assertions vs Type Guards
Prefer runtime checks over assertions where possible.
Two Ways to Convince the Compiler
When the compiler doesn't know a value's exact type, you have two options: assert it (claim the type) or guard it (prove the type at runtime). They look similar but offer very different safety.
function viaAssert(v: unknown): number {
return (v as number) + 1; // claim
}
function viaGuard(v: unknown): number {
return typeof v === 'number' ? v + 1 : 0; // prove
}
console.log(viaAssert(5), viaGuard(5), viaGuard('x'));Assertions Don't Verify
An assertion is a promise with no enforcement. If you're wrong, the bug slips through to runtime. Assertions trade safety for convenience.
const v: unknown = 'hello';
const n = v as number;
console.log(n.toFixed(2)); // runtime error: toFixed is not a functionAll lessons in this course
- The as Keyword for Type Assertions
- Non-null Assertion Operator
- Double Assertions and Their Risks
- Assertions vs Type Guards