What is type inference in TypeScript?

Type inference is the ability of a programming language to determine the data type of an expression automatically without explicit type annotations.

Type inference in TypeScript

In addition to explicit type annotations, TypeScript supports type inference, allowing less verbose code. Consider the following example:

let x = 3; // x is a number
let y = "Hello"; // y is a string
let z = true // z is a boolean
console.log(typeof x);
console.log(typeof y);
console.log(typeof z);

In the code above, we declare 3 variables x, y, and z without explicitly mentioning the data type of either of them. Upon compilation, TypeScript infers the data type of each of these variables based on the values assigned to them.

Let's see what happens if we try to assign a string to the variable x in the same code.

let x = 3; // x is a number
let y = "Hello"; // y is a string
let z = true // z is a boolean
x = "Educative" // This line will result in an error
console.log(typeof x);
console.log(typeof y);
console.log(typeof z);

If we run this code, we'll get the error:

Type 'string' is not assignable to type 'number'.

This is because on line 1, we implicitly declare the data type of x as a number. When we try to assign a different data type to variable x, we get a type mismatch error. This is an evidence that TypeScript infers the data type of variables based on their values.

Advantages of type inference

Here are some of the benefits of type inference:

  • Concise syntax: Type inference allows brevity since we do not need to explicitly declare the data types of variables.

  • Early error detection: TypeScript's type inference system infers the data types of variables at compile-time, leading to early error detection in case of type inconsistencies.

  • Readability: Type inference also improves code readability by eliminating the need for type annotations.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved