Type casting is a way to tell the compiler what the type of a variable should be, especially when the default inference isn't sufficient or accurate.
let data: any = "Hello, TypeScript!";
let length = (data as string).length;This is the most common and recommended form of casting:
let value: unknown = "42";
let strValue = value as string;
console.log(strValue.length);This works similarly to 'as', but is not valid in .tsx/JSX environments:
let age = <number>value;Note: This form should be avoided in React applications.
Type assertions help when narrowing from a broad type:
function handle(input: any) {
let trimmed = (input as string).trim();
console.log(trimmed);
}Useful when accessing DOM elements and needing specific HTML element types:
let inputElement = document.getElementById("username") as HTMLInputElement;
console.log(inputElement.value);as instead of angle-brackets in JSX/React projects.Ask the AI if you need help understanding or want to dive deeper in any topic