Type Assertion in TypeScript
Type Assertion allows you to manually tell TypeScript to treat a value as a specific type, useful in situations where you are confident in the type but TypeScript cannot infer it.
🧠Main idea:
Type Assertion lets you manually tell TypeScript: 'Trust me, I know what I'm doing — treat this value as a specific type.'
Syntax: There are two ways to do type assertion:
- Angle-bracket syntax (mostly in .ts files, not allowed in .tsx files):
as
syntax (recommended and works everywhere):
Example 1: DOM Manipulation When querying DOM elements, TypeScript only knows it returns a general Element, but you might know it's an HTMLInputElement.
Example 2: Narrowing unknown types When working with unknown or APIs, you might assert the type:
Important: Type Assertion doesn't do real conversion! It does NOT change the runtime type — it only tells TypeScript to treat it differently for type checking.