On this Page
On this Guide
- Lesson 01: What is TypeScript and Why Use It
- Lesson 02: Setting Up TypeScript in Your Project
- Lesson 03: Basic Types and Type Annotations
- Lesson 04: Functions and Type Inference
- Lesson 05: Objects, Interfaces, and Optional Properties
- Lesson 06: Arrays, Tuples, and readonly
- Lesson 07: Union, Intersection, and Literal Types
- Lesson 08: Type Aliases vs Interfaces
- Lesson 09: Working with Enums
- Lesson 10: Type Assertions and Type Casting
What is Type Assertion?
Type assertion tells TypeScript:
> “I know better than you what this type really is.”
It’s used when you want to override the compiler’s inferred type.
Using as Syntax
The most common form:
const input = document.getElementById("username") as HTMLInputElement;
console.log(input.value); // Type-safe access to .value
You can also use the older angle-bracket syntax:
const el = <htmldivelement>document.querySelector(".box");
> ⚠️ Avoid angle brackets in JSX/React files — it conflicts with syntax.
When to Use Type Assertions
Use assertions when:
- Working with DOM elements
- Receiving external data (e.g., from
JSON.parse) - You know more than TypeScript’s inference engine
Example:
const data = '{"name":"Lior"}';
const user = JSON.parse(data) as { name: string };
Non-null Assertion (!)
If you’re sure a value isn’t null or undefined:
const btn = document.querySelector("button")!;
btn.click();
> ⚠️ Dangerous if the element is not guaranteed to exist.
Forced Casting with unknown
If a value is unknown, you must assert it:
const val: unknown = "hello";
const len = (val as string).length;
For multiple steps, cast through unknown:
const user = "admin" as unknown as boolean;
> This is sometimes useful — but also a red flag. Use with care.
Avoiding Type Assertion Abuse
Don’t use assertions to silence errors:
// 🚫 Don't do this:
const num = "123" as unknown as number;
Use type guards, refinements, or safeParse methods instead.
Summary
- Type assertions override TypeScript’s inference when you’re sure of the type
- Use
assyntax for DOM, JSON, or dynamic content - Be cautious with
!and double-casting — they skip safety - Use assertions sparingly and intentionally
Next up: Lesson 11 – Generics in Functions and Interfaces — the gateway to reusable, type-safe logic.