Prefer Type Guards Over Assertions
What you'll learn: Why explicit type guards are safer and more maintainable than type assertions for narrowing types.
The Core Principle
Type assertions tell TypeScript "trust me, I know better than you," while type guards prove to TypeScript that a value has a certain type through runtime checks. Assertions bypass the type system; guards work with it.
Think of assertions like forcing a door open with a crowbar—you'll get through, but you might break something. Type guards are like using the correct key: the door opens safely because you've verified you have the right one.
Why Type Guards Win
Assertions provide zero safety:
function processValue(value: unknown) {
const str = value as string;
return str.toUpperCase(); // Runtime error if value isn't a string!
}
Type guards verify at runtime:
function processValue(value: unknown) {
if (typeof value === 'string') {
return value.toUpperCase(); // Safe: typeof checked it
}
throw new Error('Expected string');
}
The assertion version compiles but crashes when given a number. The type guard version catches the problem immediately with actual validation.
When Assertions Seem Tempting
You might reach for as when TypeScript "doesn't understand" your code. Usually, that's a signal to add explicit runtime checks instead—checks that protect your code in production, not just during compilation.
Key Takeaway: Type guards validate types at runtime and narrow safely; assertions silence the compiler without adding safety. Always prefer guards unless you have absolute certainty and no alternative.