...

/

Using type assertions

Using type assertions

In this lesson, we'll learn how to use type assertions to narrow the type of a variable.

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:

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 than ...