Type Inference

In TypeScript, type annotation is not always required. The TypeScript compiler can deduce the type information automatically when explicit type annotations are absent.

In TypeScript, TypeScript compiler infers the type information when:

  • Variables and members are initialized
  • Setting default values for parameters
  • Determined function return types

For example

Example

let x = 3;

In the previous statement, the variable "x" is inferred to be of a numerical type. This type inference occurs during the initialization of variables and members, when establishing default values for parameters, and while determining the return types of functions.

Let us take another example.

Example

var x = "TypeScript Tutorial";
var y = 501;
x = y; // Compile-time Error: Type 'number' is not assignable to type 'string'

In the preceding example, an error occurs due to TypeScript inferring the variable "x" as a string and "y" as a number. When we attempt to assign the value of y to x, the compiler raises an error indicating that a number type cannot be assigned to a string type.

Best Common Type: Type Inference

Type inference plays a crucial role in type-checking when explicit type annotations are absent. In the process of type inference, it is possible for an object to be initialized with various types.

For example

Example

let arr = [ 10, 20, null, 40 ];

In the preceding example, an array is presented containing the values 10, 20, null, and 30. In this case, we have specified two possible types for the array: number and null. The algorithm for determining the best common type selects the one that is compatible with both types, namely, number and null.

Let us take another example.

Example

let arr2 = [ 10, 20, "TypeScript Tutorial" ];

In the example provided, the array consists of elements of both number and string types. The TypeScript compiler applies the most common type algorithm to determine a type that is compatible with all included types. Consequently, the compiler interprets the type as a union of all the types present in the array. In this instance, the type would be (string | number), indicating that the array can accommodate either string or numeric values.

The return type of a function can also be deduced from the value it returns. For instance:

Example

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 previous instance, the return type for the function sum is number. Consequently, its output will be assigned to a variable of the number type, rather than a variable of the string type.

Input Required

This code uses input(). Please provide values below: