Javatpoint Logo
Javatpoint Logo

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

For example

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.

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.

For example

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.

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:

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.





Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA