TypeScript tutorial (Step by Step)

Typescript is a typed superset of JavaScript that compiles to plain JavaScript. It is pure object oriented with classes, interfaces and statically typed like C#. This tutorial will help you to learn typescript step by step. With little JavaScript knowledge, you can learn TypeScript by reading this tutorial. This tutorial will help you to know everything about TypeScript.

If you are working with SharePoint framework development, then TypeScript is necessary to learn. Here we will read from basic to advanced level in TypeScript.

What is TypeScript?

Typescript is a typed superset of JavaScript that compiles to plain JavaScript. It is pure object oriented with classes, interfaces and statically typed like C#.

It was developed by Anders Hejlsberg, who also led the creation of the C# language.

You may like following TypeScript Tutorials:

Why TypeScript?

TypeScript can be used to develop both the client side of an application, with frameworks like AngularJS or React.js, as well as the server side, with frameworks such as Node.js.

It is now considered as the most opted for language to build end-to-end applications.

A “no type system” means, a variable in JavaScript can have any type of value such as string, number, etc. The type system increases the code quality, readability and makes it an easy to maintain and refactor code base.

The most important thing here in typescript is, errors can be caught at compile time rather than at the run time.

How to use TypeScripts?

A typescript code written in a file and save with .ts extension and then compiled into JavaScript using the Typescript compiler. The Typescript compiler can be installed on any Operating System such as Windows, Mac-OS, and Linux.

It can be written in any code editor like a visual studio or visual studio code or Notepad++. The command tsc <filename>.ts compiles your Typescript code into a plain JavaScript file.

Advantages of TypeScript

  • TypeScript is purely object-oriented programming.
  • Typescript can be used for client-side and server-side development alike.
  • The ability to compile down to a version of JavaScript that runs on all browsers.
  • One of the biggest advantages of TypeScript is its code completion and IntelliSense. Intellisense provides active hints as the code is added.
  • ECMAScript 6 Feature Support Static Type-checking, TypeScript compiler will check the type (to surface more typing errors at compiling time). This is not available in JavaScript.

Difference between TypeScript and JavaScript

  • TypeScript is known as Object-oriented programming language whereas JavaScript is a scripting language.
  • TypeScript has a feature known as Static type-checking but JavaScript does not have this feature.
  • TypeScript gives support for modules whereas JavaScript does not support modules.
  • TypeScript has Interface but JavaScript does not have Interface.
  • TypeScript support optional parameter function but JavaScript does not support optional parameter function.

Environment Setup for TypeScript

There are two ways, we can install TypeScript:

  • npm
  • Visual Studio Plugin

The plugin available for Visual Studio 2019/2017 and also for Visual Studio Code. Download Link.

Install Node.js:

Node.js is an open source, a cross-platform runtime environment for server-side JavaScript. The Node.js framework is available for a variety of operating systems right from Windows to Ubuntu and OS X. To download and installs Node.js click on here- https://nodejs.org/en/

Step 1: Download and run the .msi installer for Node. download 32-bit or 64-bit based on the operating system installed in your machine.

install nodejs on windows
install nodejs on windows

Step 2: To verify if the installation was successful, enter the command “node –v” in the terminal window.

install nodejs windows
install nodejs windows

Step-3: Type the following command in the terminal window to install TypeScript.
npm install -g typescript

Step 4: To verify if the installation was successful, enter the command “tsc -v” in the terminal window. It will display the version of typescript which is recently installed on your machine.

typescript version
typescript version

Install visual Studio code:

This is an open source IDE from Visual Studio. You can download and install it from https://code.visualstudio.com/

visual studio code download
visual studio code download

You can download latest version of typescript (TypeScript 3.4).

Create and Run your First TypeScript file using Visual Studio Code

Step 1: Open the command prompt window, create a directory name called “typescript” and change the directory path as shown below.

C:\SPFx>md typescript
C:\SPFx>cd typescript

Step 2: Open “vs code” using command “code .” on command prompt.

C:\SPFx\Typescript>code .
C:\SPFx\Typescript>

Step 3: Now the Visual Studio Code is opened.

typescript tutorial
typescript tutorial

Step 4: Create a file and save with .ts extension.

typescript programming in visual studio code
typescript programming in visual studio code

Step 6: Copy and Paste the below code in Sample.ts file.

var text1: string = "Welcome To"; 
var text2: string = "TypeScript"; 
console.log(text1 + " " + text2);
visual studio code typescript compile
visual studio code typescript compile

Step 7: now compile the file using the following command. It will generate the same named JavaScript file.

tsc Sample (or) tsc Sample.ts

typescript for beginners
typescript for beginners

Step 8: Now, run that (Sample.js) file as a node server using the following command. The output is displayed as shown below.

node Sample (or) node Sample.js

typescript tutorial for beginners
typescript tutorial for beginners

Note: Do not run the command “node Sample.ts” It will throw an error message like “Unexpected token:” as shown below.

typescript tutorials for beginners
typescript tutorials for beginners

TypeScript Basics

Below, we will see some basics of TypeScript.

TypeScript Type Annotation

Unlike JavaScript, in TypeScript, we can specify the type of variables (like number, string, boolean ), function parameters, etc, because TypeScript is a typed language. But JavaScript is not a typed language.

Below is how we can use TypeScript Type Annotation in variables, function parameters and in objects.

We can specify the type using “: Type” after the name of the variable, parameter or property. There can be a space after the colon.

Example: var name: string = “bijay”; //string variable

The following example demonstrates the type annotation of parameters.

function function-name(id:number, name:string)
{
//code
}

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

var product : {
productid: number;
productname: string;
};

product = {
productid : 1001,
productname : “mobile”
}

Here, we declare an object product with two properties productid and productname with the data type number and string respectively.

TypeScript Type Inference

In TypeScript, there are several places where type inference is used to provide type information when there is no explicit type annotation.

In most cases, type inference is straightforward. For example, in this code

let name = “TSInfo”;

The type of the “name” variable is inferred to be a string. This kind of inference takes place when initializing variables and members, setting parameter default values, and determining function return types.

TypeScript Variables

In TypeScript, Variables can be declared using let,var, and const keywords.

var: We can declare a variable in typescript using “var”, the same as in JavaScript. it’s scoping rules also the same as in JavaScript.

variable declaration of var is:

Example: var name: string = “TSInfo”;

Let: The let declarations follow the same syntax as var declarations. The scope of the let variable is limited to their containing block, e.g: function, if else, etc.

variable declaration of let is:

let companyName = "TSINfo";
// or 
let companyName:string = "TSInfo";

variable declaration of let in function:

function demo() {
    if(true) { 
        let empName:string = 'Bijay';//we can access this variable here only
                                       not outside of the "if" block.       //code       
    }
    //code
}

Const: Variables can be declared using const similar to var or let declarations.

Example: const num: number = 20; //correct

“Const” variables must be declared and initialized in a single statement. Separate declaration and initialization is not supported.

Example: const num: number ; //error: ‘const’ declarations must be initialized.ts(1155)

Scope of the TypeScript variable

The scope is a specific block of the code where a variable can be accessed. There are three types of TypeScript variables based on the scope. They are :

  • Global scope: Variables that do not belong to any class and can be accessed from any part of the code.
  • Class scope: These variables are members of the class and can be accessed by the member functions of that class.
  • Local Scope: Local variables are accessible only within the construct where they are declared. The construct can be a loop, function, if block, case block, etc.

Example:

var global_scope_str = 'Hi'      //global variable 

class Strings { 
   class_scope_str = 'TSInfo';   //class variable 
   
   storeString():void { 
      var local_scope_str ='TypeScript'; //local variable

      console.log("Class Scope: " + this.class_scope_str )
      console.log("Local Scope: " + local_scope_str )           
   } 
} 

console.log("Global String: "+ global_scope_str)  
var obj = new Strings(); 
obj.storeString();
console.log("Class Scope: "+ obj.class_scope_str)

//output:
Global String: Hi
Class Scope: TSInfo
Local Scope: TypeScript
Class Scope: TSInfo

TypeScript Operators

The major operators in TypeScript are below:

  • Arithmetic operators
  • Logical operators
  • Relational operators
  • Bitwise operators
  • Assignment operators
  • Ternary/conditional operator
  • String operator
  • Type Operator
  • Arithmetic Operators

Arithmetic operators: Arthmetic operators are +(Addition),- (Subtraction),* (Multiplication),/ (Division),% (Modulus),++ (Increment),– (Decrement).

Example:

var n1:number = 20 
var n2:number = 4
var result:number = 0
 
result = n1 + n2 
console.log("Sum:        "+result); 

result = n1 - n2; 
console.log("Difference: "+result) 

result = n1*n2 
console.log("Product:    "+result) 

result = n1/n2 
console.log("Quotient:   "+result)
 
result = n1%n2 
console.log("Remainder:   "+result) 

n1++ 
console.log("Value of n1 after increment "+n1) 

n2-- 
console.log("Value of n2 after decrement "+n2)

//output:

Logical operators: Logical operators are && (And) ,|| (OR) and ! (NOT).

Example:

var n1:number = 40; 
var n2:number = 30; 

console.log("n1: "+n1+" ,n2: "+n2);
 
var result:boolean = ((n1>20)&&(n2>30)); 
console.log("("+n1+">20)&&("+n2+">30): ",result);

var result:boolean = ((n1>20)||(n2>30)); 
console.log("("+n1+">20)||("+n2+">30): ",result);

var result:boolean=!(n1>30); 
console.log("!("+n1+">30): ",result);

//output:
n1: 40 ,n2: 30
(40>20)&&(30>30):  false
(40>20)||(30>30):  true
!(40>30):  false

Relational operators: Relational operators are >(Greater than),<(Lesser than),>=(Greater than or equal to),<=(Lesser than or equal to),==(Equality) and !=(Not equal)

Example:

var n1:number = 10;
var n2:number = 20;
var result;
 
result = n1>n2 
console.log(n1+" greater than "+ n2+": "+result)

result = n1<n2 
console.log(n1+" lesser than "+n2+": "+result)  

result = n1>=n2 
console.log(n1 +" greater than or equal to " +n2+": "+result)

result = n1<=n2
console.log(n1+" lesser than or equal to "+n2+": "+result)  

result = n1==n2 
console.log(n1+" is equal to "+ n2+": "+ result)  

result = n1!=n2  
console.log(n1+" is not equal to "+ n2+": "+result)

//output:
10 greater than 20: false
10 lesser than 20: true
10 greater than or equal to 20: false
10 lesser than or equal to 20: true
10 is equal to 20: false
10 is not equal to 20: true

Bit-wise operators: Bit-wise operators are

  • & (Bitwise AND) -It performs a Boolean AND operation on each bit of its integer arguments. Follow the below table you can understand the working of “&” operator.
ABA & B
000
010
100
111
  • | (BitWise OR) -It performs a Boolean OR operation on each bit of its integer arguments.
ABA | B
000
011
101
111
  • ^ (Bitwise XOR) -It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both.
ABA ^ B
000
011
101
110
  • ~ (Bitwise Not) -It is a unary operator and operates by reversing all the bits in the operand.
A~ A
01
10
  • << (Left Shift) -It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and so on.
  • >>(Right Shift) -Binary Right Shift Operator. The left operand’s value is moved right by the number of bits specified by the right operand.
  • >>>(Right shift with Zero)-This operator is just like the >> operator, except that the bits shifted in on the left are always zero.
var n1:number = 15;   // Bit presentation 1111 
var n2:number = 13;   // Bit presentation 1101
var n3:number = 2; 
var result; 
     
result = (n1 & n2);     
console.log("("+n1+" & "+ n2+") => ",result)
          
result = (n1 | n2);          
console.log("("+n1+" | "+ n2+") =>",result)  
       
result = (n1 ^ n2);  
console.log("("+n1+" ^ "+ n2+") => ",result);
 
result = (~n2); 
console.log("(~ "+n2+") => ",result);

result = (n1 << n3); 
console.log("("+n1+" << "+ n3+") => ",result); 

result = (n2 >> n3); 
console.log("("+n2+" >> "+ n3+") => ",result);

//output:
(15 & 13) =>  13
(15 | 13) => 15
(15 ^ 13) =>  2
(~ 13) =>  -14
(15 << 2) =>  60
(13 >> 2) =>  3

Assignment operators: Assignment operators are =(Simple Assignment),+= (Add and Assignment),-= (Subtract and Assignment),*= (Multiply and Assignment) and /= (Divide and Assignment)

Example:

var n1: number = 5
var n2: number = 3  

n1 = n2
console.log(+n1+ "=" +n2+": "+n1)

var a=n1;
n1 += n2
console.log(+a+ "+=" +n2+": "+n1)

a=n1;
n1-=n2 
console.log(+a+ "-=" +n2+": "+n1)

a=n1;
n1*=n2
console.log(+a+ "*=" +n2+": "+n1)

a=n1;
n1/=n2 
console.log(+a+ "/=" +n2+": "+n1)   

a=n1;
n1%=n2
console.log(+a+ "%=" +n2+": "+n1)

//output:
3=3: 3
3+=3: 6
6-=3: 3
3*=3: 9
9/=3: 3
3%=3: 0

Ternary/conditional operator :

The ternary conditional operator(?) is not a statement but it creates conditional logic. It is used to assign a certain value to a variable based on a condition.

It will return the value on the left of the colon ( : ) if the expression is true, and return the value on the right of the colon if the expression is false.

Syntax: condition ? result1 : result2;

Example:

var n1:number = 50 
var n2:number = 30
var result = n1> n2 ?" n1: "+n1:" n2: "+n2;
console.log(result)

//output:
n1: 50

String operator: The “+ ” operator when applied to strings appends the second string to the first.

Example:

var message:string = "hello"+"Typescript" 
console.log(message)

//output: helloTypescript

Type operators in TypeScript

typeof operator: It is a unary operator. This operator returns the data type of the operand.

Example:

let str = 'hi' 
console.log(typeof str);

//output: 
string

instanceof operator: This operator can be used to test if an object is of a specified type or not.

Example: using the instanceof operator in class.

class Employee{ } 
var objEmp = new Employee() 
var isEmployee = objEmp instanceof Employee; 
console.log(" objEmp is an instance of Employee - " + isEmployee);

//output: 
objEmp is an instance of Employee - true

TypeScript Loops

A loop statement allows us to execute a statement or group of statements multiple times. TypeScript provides different types of loops to handle looping requirements.

Definite Loop in TypeScript

for loop in TypeScript

It is used to execute a block of code a given number of times, which is specified by a condition. Below is an example of for loop in TypeScript.

Syntax:

for (first expression; second expression; third expression ) {
     // statements
 }

Example:

var count:number = 1
for(let i=count; i<=5; i++){
   console.log(i)
}

//output:
1
2
3
4
5

for..of loop in TypeScript

Typescript includes the “for…of” loop to iterate and access elements of an array, list, or tuple collection. Below is an example of for…of loop in TypeScript.

Example:

var arr:string[] = ['Ind','Aus','Eng']
 
for(var item of arr){
    console.log(item)
}

//output:
Ind
Aus
Eng

for…in Loop in TypeScript

This can be used with an array, list, or tuple. The “for…in” loop iterates through a list or collection and returns an index on each iteration. Below is an example of for…in loop in TypeScript.

Example:

var arr:string[] = ['Ind','Aust','Eng']
 
for(var item in arr){
    console.log(arr[item])
}

//output:
Ind
Aus
Eng

while loop in TypeScript

While loop checks for a specified condition before beginning to execute the block of statements. The loop runs until the condition value is true.

Below is an example of while loop in TypeScript.

Syntax:

while (condition expression) {
    // code block 
}

Example: Example of Fibonacci serious

var i:number =0; 
var fib:number = 1; 
var fib1:number;

while(i<=5) {
   console.log(i+'\n')
   fib1=i+fib;
   i=fib;
   fib=fib1;
}

//output:
0
1
1
2
3
5

do..while loop in TypeScript

The do..while loop is similar to the while loop, but It runs the block of code at least once before checking for the specified condition. Below is an example of do..while loop in TypeScript.

do{
    // code block 
} while (condition expression) 

Example: Fallow the same Example of while loop using do..while.

var i:number =0; 
var fib:number = 1; 
var fib1:number;

do{
   console.log(i+'\n')
   fib1=i+fib;
   i=fib;
   fib=fib1;
} while(i<=5);

//output:
0
1
1
2
3
5

TypeScript IF Statements

A decision-making construct evaluates a condition before the instructions are executed. Decision-making constructs in TypeScript are classified as

if Statement in TypeScript

An ‘if’ statement consists of a Boolean expression followed by one or more statements.

Syntax:

if(boolean_expression) {
   // statement(s) will execute if the boolean expression is true  
} 

Example:

let  num:number = 1
if (num > 0) { 
   console.log(num + " is greater than zero ") 
}

if…else Statement in TypeScript

An ‘if’ statement can be followed by an optional ‘else’ statement, which executes when the Boolean expression is false.

Syntax:

if(expression) {
     /* if block statements */
} else {
     /* else block statements */
}

Example:

let num:number = 5; 
if (num % 2==0) { 
   console.log("Even"); 
} else {
   console.log("Odd"); 
}

Nested if Statement(if else if) in TypeScript

You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s).

Syntax:

if (expression1) { 
   //statements executes if the expression1 evaluates to true 
} else if (expression2) { 
   //statements executes if the expression2 evaluates to true 
} else { 
   //statements executes if both expression1 and expression2 result to false 
}

Example:

let a:number = 10
let b:number = 20
 
if(a == b){
    console.log("a and b are equal.")
} else if (a>b) {
    console.log("a is greater than b.")
} else if (a<b) {
    console.log("a is less than b.")
}

TypeScript Switch

The switch statement is used to check for multiple values and executes sets of statements for each of those values.

A switch statement has one block of code corresponding to each value and can have any number of such blocks. When the match to a value is found, the corresponding block of code is executed.

Syntax:

switch(expr) {
case const-expr1: {
//statements;
break;
}
case const_expr2: {
//statements;
break;
}
default: {
//statements;
break;
}
}

Example:

let a:number = 5
let b:number = 2
 
switch (a*b){
    case 7: {
        console.log("a*b is 7")
        break
    }
    case 10 : {
        console.log(" a*b is " + a*b)
        break
    }
    case 15 : {
        console.log("a*b is 15")
        break
    }
    
    default: {
        console.log("a*b is 20")
        break
    }
}

//output:
a*b is 10

TypeScript Data Types

Typescript provides different data types as a part of its optional Type System. The data type classification is:

Any: The “any “data type is the super type of all types in Typescript. If a variable is declared with “any” data type then we can assign any type value to that variable

Example: let a: any =123;

Built-in types: Typescripts has some pre-defined data-types. The key words are number,string,void,boolean,null,undefined and any.

User-defined types: It include Enumerations (enums), classes, interfaces, arrays, and tuple.

TypeScript Function

Functions are the primary blocks of any program. Functions ensure that the program is maintainable and reusable, and organized into readable blocks.

Typescript functions can be created either as Named function or as an anonymous function.

TypeScript Named Function

A named function is one where you declare and call a function by its given name. Follow the below examples you can understand easily about function in TypeScript.

Example 1: Function without parameters.

function Demo(){
    console.log("Welcome to react");
}
Demo();//output : Welcome to react

Example 2: Function with Parameters.

function Demo(name:string):void{
    console.log("Hi"+ " " + name);
}
Demo('TSInfo');//output: Hi TSInfo

TypeScript Anonymous Function

In TypeScript, an anonymous function is one which is defined as an expression. This expression is stored in a variable.

Example 1: Function without parameters.

var Demo = function(){
    console.log("Welcome to react");
}
Demo();//output: Welcome to React

Example 2: Function with parameters.

var Demo = function(name:string):void{
    console.log("Hi"+ " " + name);
}
Demo('TSInfo');//output: Hi TSInfo

Optional Parameters: The parameters that may or may not receive a value can be appended with a ‘?‘ to mark them as optional.

Example:

function Demo(text: string, name?: string ) : void {
    console.log(text + ' ' + name + '!');
}
Demo('hello');//output: hello undefined
Demo('hello','TSInfo'); //output: hello TSInfo

Default parameters:

Default parameters have the same behavior as optional parameters. TypeScript provides the option to add default values to parameters. So, if the user does not provide value to an argument, TypeScript will initialize the parameter with the default value.

Follow the below example you can understand easily about default parameters.

Example:

function Demo(text: string='Hello', name?: string ) : void {
    console.log(text + ' ' + name + '!');
}
Demo('Hi','TSInfo');//output: hi TSInfo
Demo(undefined,'TSInfo');//output:Hello TSInfo
Demo('','TSInfo');//output: TSInfo

Typescript Arrow Functions

Using the arrow (=>) we drop the need to use the ‘function’ keyword. follow the below example you can understand using the arrow instead of function keyword.

Example 1: Arrow Function without parameters.

var Demo = () => {
    console.log("Welcome to react");
}
Demo();//output: Welcome to react

Example 2: Arrow function without parameters and curly braces.

var Demo = () => console.log("Welcome to react");
Demo(); //output:  Welcome to react 

Example 3: Arrow function with parameters.

var Demo = (name:string)=>{
    console.log("Hi"+ " " + name);
}
Demo('TSInfo');//output : Hi TSInfo

TypeScript Arrays

An array is a user-defined data type. An array is a homogeneous collection of similar types of elements that have a contiguous memory location and which can store multiple values of different data types in TypeScript.

There are two ways to declare an array in typescript:

  • Using square brackets ‘[]’:

Example: let country: string[] = [‘India’, ‘Australia’, ‘England’];

  • Using a generic array type: Typescript array can contain elements of different data types, as shown below.

Example: var values: (string | number)[] = [‘India’, 1, ‘Australia’, 2, 3, ‘England’];
// or
var values: Array = [‘India’, 1, ‘Australia’, 2, 3, ‘England’];

TypeScript Tuples

As we know array consists value of Homogeneous types but sometimes we need to store a collection of a different type value in a single variable. Then we will go with Tuples.

In JavaScript, we don’t have tuples as data types, but in typescript Tuples facility is available.

Syntax: var tuple_name = [field1, field2, field3.., fieldn]

Example:

let arrTuple = [1, "Hi", 2, "lakshmi"];

console.log(arrTuple)
console.log(arrTuple[0])

//output:
[1, "Hi", 2, "lakshmi"]
1

Declaration and initialization of a tuple separately in typescript as shown below.

Example: let arrTuple = [];
arrTuple[0] = India
arrTuple[1] = Australia

Operation on tuple: A tuple has two operations: push() and pop().

Push(): To add an element to the tuple with push operation.

Example:

var country = [1, "India"];
country.push(2, "Australia"); 
console.log(country); 

//output:
[ 1, 'India', 2, 'Australia' ]

Update or Modify the Tuple Elements:

We need to use the index of the fields and assignment operator for modifying the fields of tuple.

Example:

let country = [1, "India"];  
country[0] = 2;
console.log(country);

//output:
[ 2, 'India' ]

Clear the fields of a Tuple:

Fields could be cleared but we cannot delete the tuple variables. To clear the fields of a tuple, assign it with an empty tuple field set as shown below:

Example:

let country = [1, "India"]; 
   country = [];  //empty tuple field
 console.log(country); 
 console.log(country[0]);
//output:
[]
undefined

pop(): It remove and returns the last value in the tuple.

Example:

var country = [1, "India",2,"Australia"];
country.pop(); 
console.log(country);
//output:
[ 1, 'India', 2 ]

TypeScript Union

A TypeScript Union variable can hold a value that belongs to one of the many declared datatypes.

Syntax:

var varname: datatype1|datatype2|……

  • “varname”- is the name of the union variable
  • datatype1|datatype2….datatypes that the variable can hold should be separated by vertical bar.

Example: Following is an example, where a variable can hold data of either number or string.

var unionVar: number|string
 
unionVar = 10
console.log(" type of unionVar is : "+ (typeof unionVar))
console.log(" value of unionVar : "+ unionVar)
 
unionVar = "TSInfo"
console.log("\n type of unionVar is : " +(typeof unionVar))
console.log(" value of unionVar : " + unionVar)

//output :
type of unionVar is : number
value of unionVar : 10

type of unionVar is: string
value of unionVar: TSInfo

Class in TypeScript

A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object.

The class in Typescript is compiled to plain JavaScript functions by the Typescript compiler to work across platforms and browsers.

Syntax : class class_name { //class scope }

The class definition can include – Fields, Constructor, and Functions.

Example 1:

class Product { 
   //field 
   productID:number; 
 
   //constructor 
   constructor(productID:number) { 
      this.productID = productID 
   }  

   //function 
   disp():void { 
      console.log("Product-ID is  :   "+this.productID) 
   } 
}

Creating Instance objects: To create an instance of the class, use the new keyword followed by the class name.

Syntax: var objectName = new className(arguments)

Example 1: var objProduct = new Product();

Example 2:

class  Products {
    pID: Number;
    pName: String;
       
    constructor(prodName: String, prodID: Number) {
        this.pID = prodID;
        this.pName = prodName;  
    }

    productInfo(): void {
        console.log(`Product ${this.pName} ID is ${this.pID}` );
    }
}
let objProducts = new Products('Laptop', 505);
objProducts.productInfo(); //output : Product Laptop ID is 505

Class Inheritance: A class inherits from another class using the ‘extends‘ keyword. Child classes inherit all properties and methods except private members and constructors from the parent class.

Syntax: class child_class_name extends parent_class_name

Example :

class Company { 
    name:string;
    country:string; 
  
    constructor(compName:string,compCountry:string) { 
       this.name = compName;
       this.country = compCountry;
    } 
 } 
  
 class IT extends Company { 
    display():void { 
       console.log("Name: "+this.name+"\n"+"Country: "+this.country);
    } 
 }
  
 var objCompany = new IT("TSInfo",'India'); 
 objCompany.display();

// output :
Name: TSInfo
Country: India

Classes Implement Interfaces: classes can also implement interfaces. fallow the syntax of class implement single interface.

interface A { 
   //code 
} 
class B implements A {  
   //code   
} 

fallow the syntax of class implement multiple interfaces.

interface A { 
   //code 
} 
interface B { 
   //code 
} 
class C implements A,B {  
   //code   
} 

Method overriding in TypeScript

Method Overriding is a mechanism by which the child class redefines the superclass’s method.

Example:

class ParentClass { 
   display():void {
      console.log("display() from ParentClass called…") 
   } 
} 

class ChildClass extends ParentClass { 
   doPrint():void { 
      super.display() 
      console.log("doPrint() from ChildClass called…")
   } 
} 

var objChildClass = new ChildClass() 
objChildClass.doPrint()

//output:
display() from ParentClass called…
doPrint() from ChildClass called…

TypeScript Interface

Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members.

The Typescript compiler does not convert the interface to JavaScript. It is just part of Typescript.

An interface is defined with the keyword ‘interface‘ and it can include properties and method declarations using a function or an arrow function.

Syntax:

interface interface_name { 
//declare properties and methods
}

The interface extends another interface: An interface can be extended by other interfaces. Typescript allows an interface to inherit from multiple interfaces.

Use the ‘extends‘ keyword to implement inheritance among interfaces.

Syntax: single interface inheritance

interface Child_interface_name extends parent_interface_name

Syntax: Multiple interface inheritance

interface Child_interface_name extends parent_interface1_name,
parent_interface2_name,….. parent_interfaceN_name

Example of Interface:

Step 1: Created a typescript file “Products.ts” in visual studio code. Now copy and paste the below code in that file.

interface product {
    productName: String;
    productID: number;
}
var productInfo= (type: product): void => {
  console.log('Product Name:'+ type.productName +"\n"+'Product ID:'+ type.productID);
};

var productdetails = {
    productName: 'samsung', 
    productID: 1001
}

productInfo(productdetails);

In the above example, we have created one interface called product. It has two properties called productName and productID.

Next, define a function which has one argument called type, and it is the type of interface product.

Step 2: Now compile that typescript file using command “tsc Products“.

Step 3: Next run the command “node Products“. Now see the following output is:

typescript interface
typescript interface

Namespace in TypeScript

A namespace can include interfaces, classes, functions, and variables to support a single or a group of related functionalities.

A namespace can be created using the “namespace” keyword followed by the namespace name.

Syntax: namespace <name> { }

The classes or interfaces which should be accessed outside the namespace should be marked with keyword “export“.

namespace Product {
export interface IProduct1 { }
export class Product2 { }
}

Follow the below syntax to access the class or interface in another namespace.

NameSpaceName.ClassName;

If the first namespace is in separate TypeScript file, then it should be referenced using triple slash(///) reference syntax.

/// reference path =”filename.ts” />

Compile the Namespace: Use the “–outFile” to generate a single .js file for a single namespace or multiple namespaces.

Syntax: tsc –outFile File.js File.ts

here in the above syntax, File.js is a name and path of the JavaScript file and File.ts is a namespace file name and path.

Below command is used to compile multiple namespaces into a single .js file.

tsc –outFile File.js File1.ts File2.ts.. FileN.ts

Nested Namespaces: We can define one namespace inside another namespace. Fallow the syntax:

namespace namespace_name { 
    export namespace namespace_name1 {
       export class class_name {    } 
    } 
 }

TypeScript Modules

Modules in TypeScript, allow you to create small units of independent and reusable code. In TypeScript, a module is a file containing values, functions or classes.

You can make some of the public, i.e. visible from other modules, by exporting them. Non exported objects are private.

Example: created a file “filename.ts”

export function add(): void {
}
// private
function log(): void {
}

The import keyword allows using the exported functions of a module. let’s create another file “mainfile.ts”

// you want to use the “add” function from the “filename.ts” module
import { add } from “./filename“;

If you want to use all the exported functions of a module, you can use the ” * ” syntax:

// Import the filename module as a *namespace*
import * as filename from “./filename”;

Type assertion in TypeScript

Type assertion allows you to set the type of a value and tell the compiler not to infer it.

There are two ways to declare type assertion in Typescript:

  • Using angular brackets “<>” syntax to show type assertion.
let code: any = 1001; 
let productCode = <number> code;
  • another way is, using the ‘as‘ syntax.
let code: any = 1001; 
let productCode = code as number;

Generics in TypeScript

Generics in TypeScript, offers a way to create reusable components. It provides a way to make components work with any data type and not restrict to one data type. So, components can be used with a variety of data types.

Example:

function getArr<T>(items : T[] ) : T[] {
   return new Array<T>().concat(items);
}

let numArr = getArr<number>([10, 20, 30]);
let strArr = getArr<string>(["Hi", "typescript"]);

numArr.push(40);//correct
//numArr.push("hello");//compile error: Argument of type '"hello"' is not assignable to parameter of type 'number'.ts(2345)
console.log(numArr);
console.log(strArr);

Generic class:

The generic type parameter is specified in angular brackets after the name of the class. A generic class can have generic fields or methods.

Example 1:

class Pair<F, S> {
   first: F;
   second: S;

   constructor(fir: F, secnd: S) {
       this.first = fir;
       this.second = secnd;
   }
}

//using generics in a function
function getArr<F, S>(pairs: Pair<F, S>[]): F[] {
   let arr: F[] = [];
   for (let i = 0; i < pairs.length; i++) {
       let first: F = pairs[i].first;
       arr.push(first);
   }
   return arr;
}

let strArray: Pair<string, boolean>[] = [new Pair('India', true),
   new Pair('Aus', false), new Pair('England', true)];

console.log(getArr(strArray));

//output:
[ 'India', 'Aus', 'England' ]

Example 2:

class Pair<F, S> {
   first: F;
   second: S;

   setKeyValue(fir: F, secnd: S): void {
       this.first = fir;
       this.second = secnd;
   }
   display():void { 
      console.log(`Key = ${this.first}, val = ${this.second}`);
  }
}
let kvp = new Pair<number, string>();
kvp.setKeyValue(1, "TSInfo");
kvp.display(); 

//output:
Key = 1, val = TSInfo

Generic Interface: The generic type can also be used with the interface. fallow the below examples.

Example: Generic Interface as Function Type:

interface KeyValueProcessor<K, V>
{
    (key: K, val: V): void;
};

function processKeyValuePairs<K, V>(key:K, value:V):void { 
    console.log(`processKeyPairs: key = ${key}, value = ${value}`)
}

let strKVProcessor: KeyValueProcessor<string, string> = processKeyValuePairs;
strKVProcessor('Hello', 'TypeScript');

let numstrKVProcessor: KeyValueProcessor<number, string> = processKeyValuePairs;
numstrKVProcessor(1, "TypeScript");

//output:
processKeyPairs: key = Hello, value = Typescript
processKeyPairs: key = 1, value = Typescript

Implement Interface: The generic interface can also be implemented in the class, the same as the non-generic interface, as shown below.

Example:

interface IKeyValueProcessor<K, V>
{
   //code
};
class keyValueProcessor implements IKeyValueProcessor<number, string>
{ 
    //CODE
}

Ambients in TypeScript

Ambient declarations files are saved with the extension (d.ts). A file with extension .d.ts must have the declare keyword prefixed to each root level definition. It makes clear to the author that there will be no code emitted by TypeScript.

Ambient declarations are a way of telling the TypeScript compiler that the actual source code exists elsewhere. It helps to seamlessly integrate other js libraries into TypeScript.

Defining Ambient:

The Ambient declaration is stored in a type declaration file with the following extension (d.ts)

Example: Text.d.ts

The above file will not be transcompiled to JavaScript. It will be used for type safety and intellisense.

The syntax for declaring ambient variables or modules will be as following:

declare module Module_Name {
}

The Ambient file should be referred to in the client’s Typescript file as shown below:

///<reference path = ” Text.d.ts” />

Example: The following example can understand the Ambient declaration. Here, we are using a third-party JavaScript library with the following code.

Arthmetic.js:

var TestMul;    
(function (TesMul) {    
   var Calc = (function () {   
      function Calc() {   
      }   
      Calc.prototype.doMul = function (a, b) {  
         return a * b;  
      }  
   })  
})  

Now Let us create an ambient declaration file.

Calcs.d.ts:

declare module TestMul {   
    export class Calc {   
       doMul(a:number, b:number) : number;   
    }  
 }  

Now, add this ambient declaration file (Calcs.d.ts) into our TypeScript file.

Main.ts:

/// <reference path = "Calcs.d.ts" />   
var objMult = new TestMul.Calc();   
console.log("Mult: " +objMult.doMul(10,10)); 

Compile execute the Main.ts file.

Components of TypeScript

The TypeScript language is internally divided into three main layers. Each of these layers is divided into sublayers or components. The Three layers are:

  • Language
  • The TypeScript Compiler
  • The TypeScript Language Services

Language:

It comprises elements like syntax, keywords, and type annotations.

The TypeScript Compiler:

The TypeScript compiler (tsc) transform the code written in TypeScript equivalent to its JavaScript code. It also performs the parsing, type checking of our TypeScript code to JavaScript code.

Compiler Configuration: The TypeScript compiler configuration is given in tsconfig.json and looks like the following:

{  
  "compilerOptions": {  
    "declaration": true,  
    "emitDecoratorMetadata": false,  
    "experimentalDecorators": false,  
    "module": "none",  
    "moduleResolution": "node",  
    "noFallthroughCasesInSwitch": false,  
    "noImplicitAny": false,  
    "noImplicitReturns": false,  
    "removeComments": false,  
    "sourceMap": false,  
    "strictNullChecks": false,  
    "target": "es3"  
  },  
  "compileOnSave": true  
}  

The TypeScript Language Services

The language service provides information which helps editors and other tools to give better assistance features such as automated refactoring and IntelliSense.

It supports the common typical editor operations like code formatting and outlining, colorization, statement completion, signature help, etc.

In the other tutorials, we will discuss more on TypeScript. Hope this typescript tutorial, helps to learn typescript.

>