Type inference is the automatic detection of types without explicitly defining the types. Typescript will attempt to detect types whenever possible automatically and will fall back to any whenever it can’t.
Take the following examples:
let x = 1; // type is infered as number
let y = "Hello World"; // type is infered as string
From the above examples, typescript will correctly infer the types of x
and y
without us having to define types explicitly. If we wanted, we could define the types explicitly for the above, as shown below:
let x : number = 1;
let y: string = "Hello World";
As you can imagine, using type inference takes the burden from us of having to state the type for each element explicitly. This can work with functions as well: