Quick Reference To TypeScript

In this article, you will learn about TypeScript.

Table of Contents

  1. What is TypeScript
  2. Data Type
  3. Enum
  4. Function
  5. Function Overloading
  6. Class & Object
  7. Constructor
  8. Inheritance
  9. Access Modifiers
  10. Static Functions & Properties
  11. Interface 

What is TypeScript?

 
TypeScript is a superset of JavaScript which is an optional static typing and class-based object-oriented programming language. There are object-oriented programming features like Class, Constructor, Object, Interface and they always support primary data type. OOP concepts may be implemented in this language. TypeScript’s code is more readable than JavaScript and it is open source and free. It is developed by Microsoft which announced it in October 2012.
 
Now, we will create a simple application.
 
Let’s get started.
 
Let’s create a new project with Visual Studio 2015 > File > New > Project.
 
New
 
Once the click OK button, a project with need TypeScript’s reference will be created.
 
reference
 
We can see in the above picture, app.css file is CSS file. You can keep your CSS style codes in this file. Let's look at app.ts. It’s a TypeScript file. The ts extension means a TypeScript file where you can always keep your TS code.
 
Create a ts file
 
Right-click on your project >>click add>>click JavaScript file and give name as“Welcome.ts”. Now, click OK.
  1. class welcome {  
  2.  element: HTMLElement;  
  3.  constructor(element: HTMLElement) {  
  4.   this.element = element;  
  5.   this.element.innerHTML = "Welcome To TypeScript";  
  6.  }  
  7. }  
  8. window.onload = () => {  
  9.  var elh = document.getElementById('divcontent');  
  10.  var _welcomeobj = new welcome(elh);  
  11. };   
We have created the Welcome class. There are element properties and a constructor which take a parameter. This parameter’s type is HTMLElement. When we create an instance of the welcome class, then it automatically calls the constructor. We have just given div id which is an index page. We know how to get div id using JavaScript. For catching div id, we have used document.getElementById. "Welcome To Typescript" has been assigned to the constructor.
 
Create an Index Page
 
Now, we will create an Index.html page for showing our result on the browser. Given below is the code.
  1. < !DOCTYPE html >  
  2.  <  
  3.  html lang = "en" >  
  4.  <  
  5.  head >  
  6.  <  
  7.  meta charset = "utf-8" / >  
  8.  <  
  9.  title > My Fisrt TypeScript 's Application</title>   <  
  10.  link rel = "stylesheet"  
  11. href = "app.css"  
  12. type = "text/css" / >  
  13.  <  
  14.  script src = "Welcome.js" > < /script>   <  
  15.  /head>    
  16.  <  
  17.  body >  
  18.  <  
  19.  h1 > My Fisrt TypeScript 's Application</h1>   <  
  20.  div id = "divcontent" > < /div>   <  
  21.  /body>    
  22.  <  
  23.  /html>    
We have just added Welcome.js reference on the index.html page. Because we have used Welcome.js for our coding, it is our Typescript file.
 
Finally, we get the result.
 
result
 

Data Types in TypeScript

 
We know that every programming language has basically two data types - primitive and custom. Here, we know the primitive data types include Boolean, Number, String, Any, Array, Enum. 
 
Syntax
 
Syntax
 
Create a ts file
  1. class DataType {  
  2.  Status: boolean = true;  
  3.  Amount: number = 100;  
  4.  Price: number = 50.5;  
  5.  Subject: string = "TypeScript";  
  6.  Value: any = 5;  
  7.  constructor() {  
  8.   console.log(this.Status);  
  9.   console.log(this.Amount);  
  10.   console.log(this.Price);  
  11.   console.log(this.Subject);  
  12.   console.log(this.Value);  
  13.  }  
  14. }  
  15. window.onload = () => {  
  16.  var val = new DataType();  
  17. }   
Let’s explain the data types.
 

Boolean

  1. Status: boolean = true;   
We can see that in the above line, the Status variable has bolo type data. If we keep string or number type data in the Status variable, then it will show an error.
 

String 

  1. Subject: string = "TypeScript";  
  2. Name: string = 'Mamun';   
String is textual data. Double quotes (“) or single quotes(‘) are used in TypeScript for defining the string. String data type shows error without double quotes or single quotes.
 

Number

 
Number is a very interesting data type in TypeScript. Number can take the form of: 
  1. Decimal
     
    decimal: number = 10;
     
  2. Hexadecimal
     
    hex: number = 0xf00d;
     
  3. Binary
     
    binary: number = 001101;
     
  4. Octal
     
    octal: number = 00744;

Enum

 
Enum is a helpful addition to the standard set of data types from JavaScript. Data is stored in enum. Enum’s data cannot be modified without enum block. Enums number their members starting from 0, by default, but it can be changed manually.
 
Create a ts file
  1. enum SalaryHead {  
  2.  Basic = 50, Houserent = 30, Medical = 10, Conveyance = 10  
  3. }  
  4. class SalaryCal {  
  5.  Gross: number = 50000;  
  6.  BasicSalary: number = (this.Gross * SalaryHead.Basic) / 100;  
  7.  Houserent: number = (this.Gross * SalaryHead.Houserent) / 100;  
  8.  Medical: number = (this.Gross * SalaryHead.Medical) / 100;  
  9.  Conveyance: number = (this.Gross * SalaryHead.Conveyance) / 100;  
  10.  constructor() {  
  11.   if ((this.BasicSalary + this.Houserent + this.Medical + this.Conveyance) == this.Gross) {  
  12.    console.log("Both are equal");  
  13.   } else {  
  14.    console.log("Both are not equal");  
  15.   }  
  16.  }  
  17. }  
  18. window.onload = () => {  
  19.  var val = new SalaryCal();  
  20. }   
Let’s explain Enum.
 
Above, we can see that we have declared enum named “SalaryHead” and assigned some enum property. When these properties are needed to be used in our application, just call enum. But enum’s property never changes without enum scope. Now, if enum’s property is called, then we get an assigned value.
 
Other code
  1. enum Status {  
  2.  IsDelete,  
  3.  IsPending,  
  4.  IsApprove  
  5. };   
Above is the Status of enum which contains three statuses, IsDelete, IsPending, and IsApprove.
 
Now, call Status[0]
 
Output
 
IsDelete
 

Function

 
What is a Function?
 
Group of statements performed together to solve a specific task. Every function should solve a single task. There are some reasons why we use function-
  • Organization
  • Re-usability
  • Testing
  • Extensibility
  • Abstraction
The function can be created in both ways, as a named function, and as an anonymous function, in TypeScript.
 
Named function without parameters -
  1. function GetFullName(): string {  
  2.  return "Toufique Rahman Tshovon";  
  3. }  
  4. var Name = GetFullName();  
  5. console.log(Name);   
Let’s explain the code.
 
GetFullName is a function name that does not use any parameter and returns string. Function and return are keywords. Return keyword returns value.
 
Output - Toufique Rahman Tshovon
 
Named function with parameters -
  1. function GetFullName(firstName: string, lastName: string): string {  
  2.  return firstName + " " + lastName;  
  3. }  
  4. var Name = GetFullName("Shamim""Uddin");  
  5. console.log(Name);   
Let’s explain this code.
 
GetFullName is a function name that has taken two parameters- firstName and lastName. Both are string types. firstName and lastName have been concatenated here.
 
Output: Shamim Uddin
 
Anonymous function without parameter-
  1. var Name = function(): string {  
  2.  return "Toufique Rahman Tshovon";  
  3. }  
  4. console.log(Name());   
Let’s explain the code.
 
There are no method names, but the Name variable holds the function to perform, which has no parameter.
 
Output: Toufique Rahman Tshovon
 
Anonymous function with parameter -
  1. var Name = function(firstName: string, lastName: string): string {  
  2.  return firstName + " " + lastName;  
  3. }  
  4. console.log(Name("Shamim""Uddin"));   
Let’s explain the code
 
There are no method names, but the Name variable holds a function to perform which has two parameters - firstName and lastName,  both string type. firstName and lastName are concatenated here.
 
Default Arguments
  1. function add(firstnumber: number, secondNumber: number = 10): number {  
  2.  return firstnumber + secondNumber;  
  3. }  
  4. console.log(add(10));   
Output: 20
 
Let’s get an explanation about code
 
We have assigned a default argument in the second number. if do not pass the second number then by default will be assigned 10, but if we pass the second number then the second number will be assigned like,
  1. function add(firstnumber: number, secondNumber: number = 10): number {  
  2.  return firstnumber + secondNumber;  
  3. }  
  4. console.log(add(10, 30));   
Output: 40
 

Function Overloading

 
Function overloading or Method overloading is able to create multiple methods of the same name with different signatures or different parameters.
 
Let’s go.
 
Given below is the code.
  1. function Add(firstNumber:number,secondNumber:number)  
  2. function Add(firstNumber:number,secondNumber:number,thirdNumber:number)  
  3. function Add(firstNumber:number,secondNumber:number,thirdNumber:number,forthNumber:number);function Add(firstNumber?:number,secondNumber?:number,thirdNumber?:number,forthNumber?:number):number{var result=0;if(firstNumber!=undefined&&secondNumber!=undefined&&thirdNumber!=undefined&&forthNumber!=undefined){result=firstNumber+secondNumber+thirdNumber+forthNumber;}else if(firstNumber!=undefined&&secondNumber!=undefined&&thirdNumber!=undefined){result=firstNumber+secondNumber+thirdNumber;}else if(firstNumber!=undefined&&secondNumber!=undefined){result=firstNumber+secondNumber;}  
  4. return result;}  
  5. console.log(Add(1,2));console.log(Add(1,2,2));console.log(Add(1,2,2,5));   
Let’s explain the code,
  1. function Add(firstNumber: number, secondNumber: number)   
Add is a function with two parameters.
  1. function Add(firstNumber: number, secondNumber: number, thirdNumber: number)  
Add is a function with three parameters.
  1. function Add(firstNumber: number, secondNumber: number, thirdNumber: number, forthNumber: number);   
Add is a function which has four parameters
 
There are three methods with the same name but they have different numbers of parameters.
  1. function Add(firstNumber ? : number, secondNumber ? : number, thirdNumber ? : number, forthNumber ? : number): number {  
  2.  var result = 0;  
  3.  if (firstNumber != undefined && secondNumber != undefined && thirdNumber != undefined && forthNumber != undefined) {  
  4.   result = firstNumber + secondNumber + thirdNumber + forthNumber;  
  5.  } else if (firstNumber != undefined && secondNumber != undefined && thirdNumber != undefined) {  
  6.   result = firstNumber + secondNumber + thirdNumber;  
  7.  } else if (firstNumber != undefined && secondNumber != undefined) {  
  8.   result = firstNumber + secondNumber;  
  9.  }  
  10.  return result;  
  11. }   
Above, we have implemented our method. The result is a variable that is assigned the value 0 by default.
 

Class & Object

 
Class
 
A class is a template that contains attributes and methods. It is a kind of custom data type which is used to create unlimited objects.
 
class
 
Fig: Class structure
 
There are three sections in the above figure.
 
Class Name
 
You have to give a name to the class. Ex-Employee.
 
Attributes
 
You have to define the class’s attributes. Let the class name be Employee. You have to brainstorm for what should be the attributes. Ex- 1. FirstName. 2. LastName.
 
Method
 
You have to define what kind of task will you perform using this class. Ex-1. GetFullName() 2. GetReverseName()
 
Object
 
An object is an individual instance that is created from a specific class.
 
Multiple object from class
 
Fig: Multiple objects from class
 
We can see in the above picture that there is one Employee class and four objects of employee class. Unlimited object can be created. So, when you need to create an object, you can create one.
 
Let’s go to the code.
  1. class Employee {  
  2.  public FirstName: string;  
  3.  public LastName: string;  
  4.  public GetFullName(): string {  
  5.   return this.FirstName + " " + this.LastName;  
  6.  }  
  7.  public GetReverseName(): string {  
  8.   var fullName = this.GetFullName();  
  9.   var reverse = '';  
  10.   for (var i = fullName.length - 1; i >= 0; i--) reverse += fullName[i];  
  11.   return reverse;  
  12.  }  
  13. }  
  14. window.onload = () => {  
  15.  var aemployee = new Employee();  
  16.  aemployee.FirstName = "Toufique";  
  17.  aemployee.LastName = "Rahman";  
  18.  var fullName = aemployee.GetFullName();  
  19.  var reverseName = aemployee.GetReverseName();  
  20.  document.getElementById('fulName').innerHTML = fullName;  
  21.  document.getElementById('reverseName').innerHTML = reverseName;  
  22. };   
Let’s explain the code.
  1. class Employee  
  2. Class Name Employee  
  3. public FirstName: string;  
  4. public LastName: string;  
  5. Both lines are class attributes.public GetFullName(): string {  
  6.  return this.FirstName + " " + this.LastName;  
  7. }  
  8. public GetReverseName(): string {  
  9.  var fullName = this.GetFullName();  
  10.  var reverse = '';  
  11.  for (var i = fullName.length - 1; i >= 0; i--) reverse += fullName[i];  
  12.  return reverse;  
  13. }   
There are two methods in the above code - GetFullName() and Ger ReverseName().
  1. var aemployee = new Employee();  
  2. Object has created which name is aemployee.aemployee.FirstName = "Toufique";  
  3. aemployee.LastName = "Rahman";   
Class’s attributes have been assigned as FirstName and LastName.
  1. var fullName = aemployee.GetFullName();  
  2. var reverseName = aemployee.GetReverseName();   
Two methods have been called and kept invariable.
  1. document.getElementById('fulName').innerHTML = fullName;  
  2. document.getElementById('reverseName').innerHTML = reverseName;   
These are simple JavaScript codes - get HTML tag and assign value.
 

Constructor

 
Constructor is one kind of special method. It is called by default when we create an object of a class.
 
Example
 
Below is the code of Employee class.
  1. class Employee {  
  2.  public FirstName: string;  
  3.  public LastName: string;  
  4.  constructor(firstName: string, lastName: string) {  
  5.   this.FirstName = firstNmae;  
  6.   this.LastName = lastName;  
  7.  }  
  8.  public GetFullName(): string {  
  9.   return this.FirstName + "" + this.LastName;  
  10.  }  
  11. }   
Call Employee class
 
class
 
Let get the code explained.
 
Above, we see that there is a constructor that has two parameters - firstName and lastName. Both parameters are assigned to the FirstName and LastName attributes of Employee class.
 
Created object of Employee class.
  1. var aemployee = new Employee("Toufique""Rahman");   
Note: 
  • Multiple constructor implementations are not allowed.
  • If the constructor is in class with the parameter, then without passing an argument, Object creation is impossible.

Inheritance

 
Inheritance is one of the basic elements of object-oriented programming language. It defines the relationship between different classes and common types. This relationship is called the IS-A Relationship.
 
Inheritance
 
Fig: Inheritance relationship between two class
 
Base Class
  1. class PermanentEmployee {  
  2.  public FirstName: string;  
  3.  public LastName: string;  
  4.  constructor(firstName: string, lastName: string) {  
  5.   this.FirstName = firstName;  
  6.   this.LastName = lastName;  
  7.  }  
  8.  public GetFullName(): string {  
  9.   return this.FirstName + " " + this.LastName;  
  10.  }  
  11.  public GetReverseName(): string {  
  12.   var fullName = this.GetFullName();  
  13.   var reverse = '';  
  14.   for (var i = fullName.length - 1; i >= 0; i--) reverse += fullName[i];  
  15.   return reverse;  
  16.  }  
  17. }   
Sub Class
  1. class TemporaryEmployee extends PermanentEmployee {  
  2.  public JobDuration: string;  
  3.  constructor(firstName: string, lastName: string) {  
  4.   super(firstName, lastName);  
  5.  }  
  6. }  
  7. var employeeObj = new TemporaryEmployee("Toufique""Rahman");  
  8. var fullName = employeeObj.GetFullName();  
  9. var reverseName = employeeObj.GetReverseName();   
Let’s explain the code.
 
Here, the Base class is PermanentEmployee.
  1. class PermanentEmployee {
Attributes
  1. public FirstName: string;  
  2. public LastName: string;  
Constructor has two parameters, firstName, and lastName. Both are assigned to attributes.
  1. constructor(firstName: string, lastName: string) {  
  2.  this.FirstName = firstName;  
  3.  this.LastName = lastName;  
  4. }   
Two methods- GetFullName,
  1. public GetFullName(): string {  
  2.  return this.FirstName + " " + this.LastName;  
  3. }   
and GetReverseName,
  1. public GetReverseName(): string {  
  2.  var fullName = this.GetFullName();  
  3.  var reverse = '';  
  4.  for (var i = fullName.length - 1; i >= 0; i--) reverse += fullName[i];  
  5.  return reverse;  
  6. }   
Sub class is TemporaryEmployee.
 
class TemporaryEmployee extends PermanentEmployee {
 
Here, the TemporaryEmployee class inherits the PermanentEmployee class using extends keyword. Now, we can access PermanentEmployee.
 
Attribute
 
public JobDuration: string;
 
Constructor
  1. constructor(firstName: string, lastName: string) {  
  2.  super(firstName, lastName);  
  3. }   
Constructor has taken two parameters. Parameters values are assigned to basic class’s constructor using super keyword.
 
TemporaryEmployee class’s object is created here.
  1. var employeeObj = new TemporaryEmployee("Toufique""Rahman");  
  2. var fullName = employeeObj.GetFullName();  
  3. var reverseName = employeeObj.GetReverseName();   
Created object employeeobj, then passed two attributes for constructor.
 
Interestingly, we can access GetFullName and GetReverseName in the subclass (TemporaryEmployee). Initially, these were defined in the base class (PermanentEmployee). Now, we can access these in subclass (TemporaryEmployee) also for IS-A Relationship.
 

Access Modifiers 

  • TypeScript has three types of access modifiers- public, private, and protected.
  • Access modifiers prevent the misuse of class members (functions and properties).
  • If we do not use any access modifier, TypeScript sets a "public access modifier" to all the class members (functions or properties), by default.
Public Access
 
If using a public access modifier, the members (functions or properties) can be accessed anywhere in the code freely. Like, Base class or Sub Class.
 
Example
 
Let's get the code explanation.
  1. class SavingAccount {  
  2.  public AccountNo: string;  
  3.  private Amount: number;  
  4.  constructor(accountNo: string) {  
  5.   this.AccountNo = accountNo;  
  6.  }  
  7.  public Deposit(amount: number): string {  
  8.   this.Amount = amount;  
  9.   return "Deposit Successfully.";  
  10.  }  
  11.  public withdraw(amount: number): string {  
  12.   this.Amount = amount;  
  13.   return "withdraw Successfully.";  
  14.  }  
  15.  public TotalAmount(): number {  
  16.   return this.Amount;  
  17.  }  
  18. }  
  19. var _savingAccount = new SavingAccount("sav0234232");  
  20. _savingAccount.Deposit(1000);  
  21. _savingAccount.withdraw(500);  
  22. _savingAccount.TotalAmount();   
All Public members in class have been called by object reference of SavingAccount class, and public members always call subclass.
 
Private Access
 
If we use a private access modifier, the members can be accessed within the self class by its other class members (functions) only.
 
Example
 
Let's get it in code.
  1. class SavingAccount {  
  2.  public AccountNo: string;  
  3.  private Amount: number;  
  4.  constructor(accountNo: string) {  
  5.   this.AccountNo = accountNo;  
  6.  }  
  7.  public Deposit(amount: number): string {  
  8.   this.Amount = amount;  
  9.   return "Deposit Successfully.";  
  10.  }  
  11.  public withdraw(amount: number): string {  
  12.   this.Amount = amount;  
  13.   return "withdraw Successfully.";  
  14.  }  
  15.  public TotalAmount(): number {  
  16.   return this.Amount;  
  17.  }  
  18. }  
  19. var _savingAccount = new SavingAccount("sav0234232");   
When we call Amount properties which are private properties, we get the error.
 
Access
 
In the above code, we can see that the Amount of property is used in TotalAmount Function which is in the SavingAccount class. So, we can easily use this Amount of property.
 
Protected Access
 
If we use a protected access modifier, the members can be accessed within the subclass. Otherwise, this access modifier cannot be accessed.
 
Example
  1. class Account {  
  2.  public AccountNo: string;  
  3.  protected Amount: number;  
  4.  constructor(accountNo: string) {  
  5.   this.AccountNo = accountNo;  
  6.  }  
  7.  public Deposit(amount: number): string {  
  8.   this.Amount = amount;  
  9.   return "Deposit Successfully.";  
  10.  }  
  11.  public withdraw(amount: number): string {  
  12.   this.Amount = amount;  
  13.   return "withdraw Successfully.";  
  14.  }  
  15.  protected TotalAmount(): number {  
  16.   return this.Amount;  
  17.  }  
  18. }   
When we call a protected members of this class by using this class’s object, we get an error.
 
error
 
Protected is like private.
 
Sub Class
  1. class SavingAccount extends Account {  
  2.  constructor(accountNo: string) {  
  3.   super(accountNo);  
  4.  }  
  5.  public TotalAmount(): number {  
  6.   return this.Amount;  
  7.  }  
  8. }  
  9. var _savingAccount = new SavingAccount("Sav-43434");  
  10. _savingAccount.Deposit(1000);  
  11. _savingAccount.withdraw(500);   
In the above code, we can see that Amount of property is used in TotalAmount function, which is protected and exists in the base class. From the above code, we know that protected member is used within Subclass, otherwise, we cannot use this.
  

Static Function & Properties

 
Static functions and properties can only be called by their class reference and cannot be called by an object reference. Sometimes, we need to void unnecessary created objects; that time, we use Static.
 
Example
  1. class Calculator {  
  2.  public static FirstNumber: number;  
  3.  public static SecondNumber: number;  
  4.  public static addTowNumber(): number {  
  5.   return this.FirstNumber + this.SecondNumber;  
  6.  }  
  7. }  
  8. Calculator.FirstNumber = 10;  
  9. Calculator.SecondNumber = 30;  
  10. Calculator.addTowNumber()   
Let’s get the code explained.
 
In the above code, there are two static properties and one static function. When those properties and functions are called, then we do not have the need for creating objects. Those are called by Class Name.
 
Like,
  1. Calculator.FirstNumber = 10;  
  2. Calculator.SecondNumber = 30;  
  3. Calculator.addTowNumber()   
Interface
 
Interface is object-oriented syntax which is used to manage application beauty. That means that the Class and Method are ready. We just call and we will implement this method by itself. The method’s name will remain the same in the whole application.
 
Interface class
  1. interface iGenericFactory {  
  2.  Save(): void;  
  3.  Update(): void;  
  4.  delete(): void  
  5. }   
Here, there are no method implementations. We can see only the method name and signature.
 
Interface Implemented
  1. class Employee implements iGenericFactory {  
  2.  public Save(): void {}  
  3.  public Update(): void {}  
  4.  public delete(): void {}  
  5. }   
Note: 
  • When we implement the interface, then we must use the implementation keyword.
  • All Methods will be implemented.
Happy Coding.