Type Assertion

Type assertion allows you to set the type of a value and tell the compiler not to infer it. This is when you, as a programmer, might have a better understanding of the type of a variable than what TypeScript can infer on its own. Such a situation can occur when you might be porting over code from JavaScript and you may know a more accurate type of the variable than what is currently assigned. It is similar to type casting in other languages like C# and Java. However, unlike C# and Java, there is no runtime effect of type assertion in TypeScript. It is merely a way to let the TypeScript compiler know the type of a variable.

image.png

image.png

let response: any = "42";

let numericLength: number = (response as string).length;

console.log(numericLength);

Let’s Look at More Examples to Understand Type Assertion Better

JSON Parsing with Type Assertion

When data is fetched from an API or a database, it's often in JSON format. TypeScript doesn't know the shape of the parsed object. You can use type assertion to help.

image.png

DOM Element Type Assertion

TypeScript doesn't know by default that this is an input element, so we assert the type to HTMLInputElement to access .value.

image.png

Challenge: Fix the Status Assignment Issue

You're building a system where user status is stored in the database as plain strings ('pending', 'declined'). However, in your TypeScript code, you want to use an enum for better type safety.

You're facing a situation where TypeScript won't let you assign that string from the database to a property typed as the enum.

image.png

Your task is to fix this error.