TypeScript Type Annotation

We know that JavaScript is not a typed language so we cannot specify the type of a variable such as a number, string, Boolean in JavaScript. However, in TypeScript, we can specify the type of variables, function parameters, and object properties because TypeScript is a typed language.

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.

We can specify the type by using a colon(: Type) after a variable name, parameter, or property. There can be a space between the colon and variable name, parameter, or property. TypeScript includes all the primitive data types of JavaScript such as number, string, Boolean, etc.


var variableName: TypeAnnotation = value;

The following example demonstrates type annotations for variables with different data types.

Example #1
var age: number = 44;          // number variable
var name: string = "Rahul";     // string variable
var isUpdated: boolean = true; // Boolean variable

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.

Example #2
function display(id:number, name:string)
    console.log("Id = " + id + ", Name = " + name);
display(101, "Rohit Sharma");
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.


:{ /*Structure*/ }
var student : { 
    id: number; 
    name: string; 

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

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.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +