4 min read
•Question 6 of 48easyWhat is Type Assertion in TypeScript?
Telling TypeScript what type a value is.
What You'll Learn
- What type assertion is
- Two syntaxes
- When to use it
Type Assertion
Type assertion tells TypeScript to treat a value as a specific type. It's like a type cast but performs no runtime checking.
Two Syntaxes
code.tsTypeScript
// as syntax (preferred)
let value: unknown = "hello";
let length: number = (value as string).length;
// angle bracket syntax (not in JSX)
let length2: number = (<string>value).length;Common Use Cases
code.tsTypeScript
// DOM elements
const input = document.getElementById("email") as HTMLInputElement;
input.value = "test@example.com";
// API responses
interface User {
name: string;
email: string;
}
const data = JSON.parse(response) as User;Caution
code.tsTypeScript
// TypeScript trusts you - be careful!
const num = "hello" as unknown as number;
console.log(num.toFixed()); // Runtime error!const Assertion
code.tsTypeScript
// Makes values readonly and literal
const colors = ["red", "green", "blue"] as const;
// Type: readonly ["red", "green", "blue"]