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.
We'll cover the following...
We'll cover the following...
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:
The example is a bit contrived, but we often do consume third party functions where the return type is wider ...