What is Type Inference in TypeScript

TypeScript is a typed language. However, it is not mandatory to specify the type of a variable. TypeScript infers types of variables when there is no explicit information available in the form of type annotations


Types are inferred when:

  • Variables are initialized
  • Default values are set for parameters
  • Function return types are determined
var a = "Typescript";
var b = 123;
a = b; // Compiler Error: Type 'number' is not assignable to type 'string'

function sum(a: number, b: number ){
return a + b;
}
var total: number = sum(10,20); // OK
var str: string = sum(10,20); // Compiler Error

When Typescript can not infer the type the any type will be used

const canNotInfer = JSON.parse('{}');
// canNotInfer will have type: any