0Pricing
TypeScript Academy · Lesson

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 function

All lessons in this course

  1. The as Keyword for Type Assertions
  2. Non-null Assertion Operator
  3. Double Assertions and Their Risks
  4. Assertions vs Type Guards
← Back to TypeScript Academy