TypeScript Type Annotation
Type Annotations are annotations which can be placed anywhere when we use a type. The use of Type annotation is not mandatory in TypeScript. It helps the compiler in checking the types of variable and avoid errors when dealing with the data types.
The following example demonstrates type annotations for variables with different data types.
In the above example, the variables are declared with their data type. These examples demonstrate type annotations. Here, we cannot change the value by using a different data type with the available data type. If we try to do this, TypeScript compiler will throw an error. For example, if we assign a string to a variable age or number to the name, then it will give a compilation error.
Use of Type Annotation as a parameter
The below example demonstrates the type annotation with parameters.
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.
Here, we declare an object student with two properties "id" and "name" with the data type number and string, respectively. If we try to assign a string value to id, the TypeScript compiler will throw an error: Type of property are incompatible.