Skip to content

FlashcardNot attempted

Assertions vs guards

Recall it before you reveal

What is the difference between a type assertion (as) and a type guard?

Space to reveal
Show answer & explanation

An assertion tells the compiler "trust me" and emits no runtime code. If you're wrong, it fails later at runtime with a confusing error.

A guard is real runtime code (typeof, instanceof, in, or a x is T predicate function) that the compiler also understands, so the narrowed type is actually true.

Prefer guards (or schema validation) at trust boundaries, and assertions only when you know more than the compiler (e.g. document.getElementById('root')!).