TypeScript Type Inference

In TypeScript, it is not necessary to annotate type always. The TypeScript compiler infers the type information when there is no explicit information available in the form of type annotations.

In TypeScript, TypeScript compiler infers the type information when:

  • Variables and members are initialized
  • Setting default values for parameters
  • Determined function return types
Example #1
let x = 3;

In the above, the type of the variable "x" infers in a number. The type inference takes place when initializing variables and members, setting parameter default values, and determining function return types.

Let us take another example.

Example #2
var x = "rookienerd";
var y = 501;
x = y; // Compile-time Error: Type 'number' is not assignable to type 'string'

In the above example, we get an error because while inferring types, TypeScript inferred the type of variable "x" as a string and variable "y" as a number. When we try to assign y to x, the compiler generates an error that a number type is not assignable to a string type.

Best Common Type: Type Inference

Type inference is helpful in type-checking when there are no explicit type annotation is available. In type inference, there can be a situation where an object may be initialized with multiple types.

Example #1
let arr = [ 10, 20, null, 40 ];

In the above example, we have an array with values 10, 20, null, and, 30. Here, we have given two choices for the type of an array: number and null. The best common type algorithm picks the one which is compatible with all types, i.e., number and null.

Let us take another example.

Example #2
let arr2 = [ 10, 20, "rookienerd" ];

In the above example, the array contains values of type number and string both. Now, the TypeScript compiler uses the most common type algorithm and picks the one which is compatible with all types. In such cases, the compiler treats the type as a union of all types in the array. Here, the type would be (string or number), which means that the array can hold either string values or numeric values.

The return type of a function is also inferred by the returning value. For example:

Example #3
function sum(x: number, y: number )
    return x + y;    
let Addition: number = sum(10,20); // Correct
let str: string = sum(10,20); // Compiler Error

In the above example, the return type of the function sum is number. So, its result will be stored in a number type variable, not a string type variable.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +