Search⌘ K
AI Features

Using type assertions

Explore how to apply type assertions in TypeScript to specify variable types when the compiler cannot infer them accurately. Understand the differences between angle-bracket and 'as' syntax and why React apps should use the 'as' syntax for type assertions. Gain practical knowledge to handle external data types confidently while avoiding runtime issues.

Understanding the need for type assertions #

Sometimes we know more about a variable value than TypeScript does. Consider the code below; it would be nice to narrow the type of the value returned from getAge to number:

TypeScript 3.3.4
function getAge(id: number): any {
return 42;
}
function calcDiscount(age: number) {
return age / 100;
}
const discount1 = calcDiscount(getAge(1));
console.log(discount1);

The example is a bit contrived, but we often do consume third party functions where the return type is wider ...