TypeScript Type Annotation and Inference
Type Annotations are annotations that can be placed anywhere we use a type. The use of Type annotation is not mandatory in TypeScript. However, it helps the compiler in checking types of variable and avoid errors in dealing with the data types.
The following example demonstrates type annotations for variables with different data types:
In the above example, the variable is declared with their data type. These example demonstrates type annotations. Here, we cannot change the value by using a different data type. If we try to do this, TypeScript compiler will show an error. For example, if we assign a string to a variable age: number to the name, then it will give a compilation error.
Use of Type Annotation as a parameter
Id = 101, Name = Rohit Sharma
Inline Type Annotation
In TypeScript, inline type annotations allow us to declare an object for each of the properties of the object.
It is not mandatory to annotate type always. In TypeScript, type inference is used to provide type information when there is no explicit information available in the form of type annotations.
In TypeScript, types are inferred by TypeScript compiler when:
In the above, the type of the variable x is inferred 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.
In the above example, we have an array with values 10, 20, null, and, 30. Here, we are given two choices for the type of the array: number and null. The best common type algorithm picks the one that is compatible with all types, i.e. number, as well as null.
Let us take another example:
In the above example, the array has values of type number and string both. In this, the TypeScript compiler looks the most common type algorithm and picks the one that 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 | 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.