TypeScript · Lesson 42 of 120
Type Assertions
As, carefully.
A type assertion tells TypeScript, trust me, I know this type better than you. It's written with as. It doesn't check or convert anything, so a wrong assertion hides real bugs.

- Trust me
- as
- No checks
A wrong assertion
We parse some JSON, and assert it's a bike. But the data has no price. TypeScript believes us, so the code compiles. Run it. The price is undefined, and the maths gives not a number.
app.tstypescript
type Bike = { model: string; price: number };
const data = JSON.parse('{"model": "Trail 500"}');
const bike = data as Bike;
console.log(bike.model, "with tax:", bike.price * 1.2);Output
Trail 500 with tax: NaN
When assertions are OK
Use them when you truly know more than the compiler, like the result of a DOM lookup. For data from outside your program, validate it instead. We'll learn how, with runtime checks and Zod.
| key | value |
|---|---|
| OK | you truly know better |
| Avoid | outside data |
| Instead | validate |
| Later | Zod |
Summary
Assertions skip checking, so use them rarely, and validate outside data instead. Next, a new section on classes.
Key takeaways- as Bike
- No checks
- Validate instead
Next up: Classes — blueprints