Ad space (banner)
Lesson 18 / 20

Type Assertions (as)

This lesson covers type assertions (as), used to tell TypeScript "trust me, this value is this type." It's for anyone searching "TypeScript as type assertion."

Using as lets you override the type TypeScript automatically inferred with one you specify yourself. This doesn't perform any runtime check, though โ€” it's purely a declaration that "the developer guarantees this."

The example treats a value of type unknown as a string with as string. Use this in situations where you're certain the value really is a string.

A common early mistake is overusing type assertions. Since as is also a way to bypass type checking, specifying a type that doesn't match the actual value becomes a source of runtime errors. Wherever possible, prefer safely narrowing the type with a type guard like typeof, covered in an earlier lesson.

In real projects, type assertions are used a lot for things like retrieving a DOM element (e.g. document.getElementById) โ€” situations where TypeScript can't fully infer a specific type on its own.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run TypeScript directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)