TypeScript - Type Annotations

JavaScript is not a typed language. It means we cannot specify the type of a variable such as number, string, boolean etc. However, TypeScript is a typed language, where we can specify the type of the variables, function parameters and object properties.

We can specify the type using :Type after the name of the variable, parameter or property. There can be a space after the colon. TypeScript includes all the primitive types of JavaScript- number, string and boolean.

The following example declares variables with different data types:

Example: Type Annotation in TypeScript
var age: number = 32; // number variable
var name: string = "John";// string variable
var isUpdated: boolean = true;// Boolean variable

In the above example, each variable is declared with their data type. These are type annotations. You cannot change the value using a different data type other than the declared data type of a variable. If you try to do so, TypeScript compiler will show an error. This helps in catching JavaScript errors. For example, if you assign a string to a variable age or a number to name in the above example, then it will give an error.

Type annotations are used to enforce type checking. It is not mandatory in TypeScript to use type annotations. However, type annotations help the compiler in checking types and helps avoid errors dealing with data types. It is also a good way of writing code for easier readability and maintenance by future developers working on your code.

We can still follow the JavaScript way of declaring variables and have the TypeScript compiler infer the data type of the variable.

The following example demonstrates the type annotation of paramters.

Example: Type Annotation of Parameters
function display(id:number, name:string)
    console.log("Id = " + id + ", Name = " + name);

Similarly, we can declare an object with inline annotations for each of the properties of the object.

Example: Type Annotation in Object
var employee : { 
    id: number; 
    name: string; 

employee = { 
  id: 100, 
  name : "John"

Here, we declare an object employee with two properties id and name with the data type number and string respectively.

If you try to assign a string value to id then the TypeScript compiler will give the following error.

error TS2322: Type '{ id: string; name: string; }' is not assignable to type 
'{ id:number; name: string; }'.Types of property 'id' are incompatible.
Type 'string' is not assignable to type 'number'.