What is type casting?

Type casting is a way to tell the TypeScript compiler that a variable or expression should be treated as a specific type, even if the compiler cannot infer the type automatically. It allows you to override the default type inference, often used when dealing with dynamic data or when interacting with APIs or libraries where the type isn’t explicitly defined.

There are two ways to cast types in TypeScript:

  1. Using as keyword:
let welcomeMessage: unknown = "Hi everyone, this is Sandeep! Welcome to my post.";
let messageLength: number = ( welcomeMessage as string ).length;

2. Using <>:

let welcomeMessage: unknown = "Hi everyone, this is Sandeep! Welcome to my post.";
let messageLength: number = ( <string>welcomeMessage ).length;