TypeScript Type Casting

What is Type Casting?

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;

Using 'as' Syntax

This is the most common and recommended form of casting:

let value: unknown = "42";
let strValue = value as string;
console.log(strValue.length);

Using Angle-Bracket Syntax

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.

Casting to More Specific Types

Type assertions help when narrowing from a broad type:

function handle(input: any) {
  let trimmed = (input as string).trim();
  console.log(trimmed);
}

DOM Element Casting

Useful when accessing DOM elements and needing specific HTML element types:

let inputElement = document.getElementById("username") as HTMLInputElement;
console.log(inputElement.value);

Best Practices

  • Only cast when you're sure of the type.
  • Use as instead of angle-brackets in JSX/React projects.
  • Avoid casting between completely unrelated types.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic