AI Hints
Home›TypeScript Tutorial›Enums and Assertions
TypeScript · Lesson 42 of 120

Type Assertions

As, carefully.

⏱ 2 min read▶ Video at 33:29🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

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.

Type Assertions
From the video: Type Assertions
  • 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.

keyvalue
OKyou truly know better
Avoidoutside data
Insteadvalidate
LaterZod

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