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:

  1. Angle-bracket syntax (mostly in .ts files, not allowed in .tsx files):
typescript
1let value = "hello" as string;
  1. as syntax (recommended and works everywhere):
typescript
1let value = <string>"hello";

Example 1: DOM Manipulation When querying DOM elements, TypeScript only knows it returns a general Element, but you might know it's an HTMLInputElement.

typescript
1const input = document.querySelector('input') as HTMLInputElement; 2input.value = "Hello world"; // No error because TypeScript knows it's an input!

Example 2: Narrowing unknown types When working with unknown or APIs, you might assert the type:

typescript
1function getValue(): unknown { 2 return "hello"; 3} 4 5const str = getValue() as string; 6console.log(str.length); // safe now

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.