- 01Getting Started
- 02Your First Output (console.log)
- 03Variables and Type Annotations (number/string/boolean)
- 04Array Types
- 05Function Types (Parameters and Return Values)
- 06Optional Parameters and Default Parameters
- 07Interfaces (interface)
- 08Optional Properties (?)
- 09Type Aliases (type)
- 10Union Types
- 11Literal Types
- 12enum (Enumerated Types)
- 13Classes and Types
- 14Inheritance (extends) and Implementing an Interface (implements)
- 15Generics (<T>)
- 16Tuple Types
- 17The any and unknown Types
- 18Type Assertions (as)
- 19The readonly Modifier
- 20[Applied] Build a Mini Inventory Management System
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.
๐งช 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).
