Type inference

While working with TypeScript, it is very common to find code as follows:

let age: number = 20; 
let existsFlag: boolean = true; 
let language: string = 'JavaScript'; 

TypeScript allows us to assign a type to a variable. But the preceding code is verbose. TypeScript has type inference, meaning TypeScript will verify and apply a type to the variable automatically based on the value that was assigned to it. Let's rewrite the preceding code with a cleaner syntax:

let age = 20; // number 
let existsFlag = true; // boolean 
let language = 'JavaScript'; // string 

With the preceding code, TypeScript still knows that age is a number, existsFlag is a boolean, and language is a string, so we don't need to explicitly assign a type to these ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.