Quick Reference To 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 concept 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 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 TypeScript file where you can always keep your TS code.

Create ts file

Right click on your project >>click add>>click JavaScript file and give name as“Welcome.ts”. Now, click OK.
  1. // Class name welcome  
  2. class welcome {  
  3.     element: HTMLElement;  
  4.     // constructor  
  5.     constructor(element: HTMLElement) {  
  6.         this.element = element;  
  7.         this.element.innerHTML = "Welcome To TypeScript";  
  8.     }  
  9. }  
  10. // window onload event, when page open then call this onload event   
  11. window.onload = () => {  
  12.     // get html divcontent   
  13.     var elh = document.getElementById('divcontent');  
  14.     // create new object and call constructor with elh paramitter  
  15.     var _welcomeobj = new welcome(elh);  
  16. };  
We have created Welcome class. There are element properties and a constructor which take a parameter. This parameter’s type is HTMLElement. When we create instance of welcome class, then it automatically calls the constructor. We have just given div id which is 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 Index Page

Now, we will create Index.html page for showing our result on browser. Given below is the code.
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3.   
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <title>My Fisrt TypeScript's Application</title>  
  7.     <link rel="stylesheet" href="app.css" type="text/css" />  
  8.     <script src="Welcome.js"></script>  
  9. </head>  
  10.   
  11. <body>  
  12.     <h1>My Fisrt TypeScript's Application</h1>  
  13.     <div id="divcontent"></div>  
  14. </body>  
  15.   
  16. </html>  
We have just added Welcome.js reference on 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 ts file

  1. class DataType   
  2. {  
  3.     // boolean Type  
  4.     Status: boolean = true// output ture  
  5.     // number Type  
  6.     Amount: number = 100; // output 100  
  7.     // number always support like decimal,hex,binary,octal  
  8.     Price: number = 50.5; // output 50.5  
  9.     // string Type  
  10.     Subject: string = "TypeScript"// TypeScript  
  11.     // any like dynamic type   
  12.     Value: any = 5;  
  13.     // we know that when class object will be Created then automatic call constructor,  
  14.     constructor() {  
  15.         console.log(this.Status);  
  16.         console.log(this.Amount);  
  17.         console.log(this.Price);  
  18.         console.log(this.Subject);  
  19.         console.log(this.Value);  
  20.     }  
  21. }  
  22. window.onload = () => {  
  23.     // Create class object   
  24.     var val = new DataType();  
  25. }  
Let’s explain the data types.

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

String 
  1. Subject: string = "TypeScript"//output is TypeScript  
  2. Name: string = 'Mamun'//output is 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 ts file

  1. enum SalaryHead  
  2. {  
  3.     // these are %  
  4.     Basic = 50,  
  5.         Houserent = 30,  
  6.         Medical = 10,  
  7.         Conveyance = 10  
  8. }  
  9. class SalaryCal   
  10. {  
  11.     // let gross salary is 50000,Gross Salary will be given from IU in real wrold   
  12.     Gross: number = 50000;  
  13.     // Calculate Basic from gross slary  
  14.     BasicSalary: number = (this.Gross * SalaryHead.Basic) / 100;  
  15.     // Calculate House Rent from gross slary  
  16.     Houserent: number = (this.Gross * SalaryHead.Houserent) / 100;  
  17.     // Calculate Medical from gross slary  
  18.     Medical: number = (this.Gross * SalaryHead.Medical) / 100;  
  19.     // Calculate Conveyance from gross slary  
  20.     Conveyance: number = (this.Gross * SalaryHead.Conveyance) / 100;  
  21.     // we can not modify enum valu without enum block  
  22.     // SalaryHead.Basic=60;  
  23.     constructor() {  
  24.         // Now we will check sum of salary head and gross are equal.  
  25.         if ((this.BasicSalary + this.Houserent + this.Medical + this.Conveyance) == this.Gross) {  
  26.             console.log("Both are equal");  
  27.         } else {  
  28.             console.log("Both are not equal");  
  29.         }  
  30.     }  
  31. }  
  32. window.onload = () => {  
  33.     // Create class object   
  34.     var val = new SalaryCal();  
  35. }  
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 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 Type Script.

Named function without parameters -

  1. function GetFullName(): string  
  2. {  
  3.     return "Toufique Rahman Tshovon";  
  4. }  
  5. var Name = GetFullName();  
  6. console.log(Name);  
Let’s explain the code.

GetFullName is a function name which 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. {  
  3.     return firstName + " " + lastName;  
  4. }  
  5. var Name = GetFullName("Shamim""Uddin");  
  6. console.log(Name);  
Let’s explain this code.

GetFullName is a function name which 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. {  
  3.     return "Toufique Rahman Tshovon";  
  4. }  
  5. 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. {  
  3.     return firstName + " " + lastName;  
  4. }  
  5. 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. {  
  3.     return firstnumber + secondNumber;  
  4. }  
  5. console.log(add(10));  
Output: 20

Let’s get an explanation about code

We have assigned default argument in secondNumber. if do not pass secondNumber then by default will be assigned 10, but if we pass secondNumber then secondNumber will be assigned like,
  1. function add(firstnumber: number, secondNumber: number = 10): number   
  2. {  
  3.     return firstnumber + secondNumber;  
  4. }  
  5. 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.   
  3. function Add(firstNumber: number, secondNumber: number, thirdNumber:number)  
  4.   
  5. function Add(firstNumber: number, secondNumber: number, thirdNumber:number, forthNumber: number);  
  6.   
  7. function Add(firstNumber ? : number, secondNumber ? : number, thirdNumber ? : number, forthNumber ? : number): number {  
  8.     var result = 0;  
  9.     if (firstNumber != undefined && secondNumber != undefined && thirdNumber != undefined && forthNumber != undefined) {  
  10.         result = firstNumber + secondNumber + thirdNumber + forthNumber;  
  11.     } else if (firstNumber != undefined && secondNumber != undefined && thirdNumber != undefined) {  
  12.         result = firstNumber + secondNumber + thirdNumber;  
  13.     } else if (firstNumber != undefined && secondNumber != undefined) {  
  14.         result = firstNumber + secondNumber;  
  15.     }  
  16.     return result;  
  17. }  
  18. console.log(Add(1, 2));  
  19. console.log(Add(1, 2, 2));  
  20. 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 same name but they have different number of parameters.
  1. function Add(firstNumber ? : number, secondNumber ? : number, thirdNumber ? : number, forthNumber ? : number): number  
  2. {  
  3.     var result = 0;  
  4.     if (firstNumber != undefined && secondNumber != undefined && thirdNumber != undefined && forthNumber != undefined) {  
  5.         result = firstNumber + secondNumber + thirdNumber + forthNumber;  
  6.     } else if (firstNumber != undefined && secondNumber != undefined && thirdNumber != undefined) {  
  7.         result = firstNumber + secondNumber + thirdNumber;  
  8.     } else if (firstNumber != undefined && secondNumber != undefined) {  
  9.         result = firstNumber + secondNumber;  
  10.     }  
  11.     return result;  
  12. }  
Above, we have implemented our method. The result is a variable which is assigned the value 0 by default.
 
Class & Object

Class

A class is a template which 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 class’s attributes. Let 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

Object is an individual instance which is created from specific class.

Multiple object from class
Fig: Multiple object 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. {  
  3.     // -----start attributes  
  4.     public FirstName: string;  
  5.     public LastName: string;  
  6.     // -----end attributes  
  7.     //------start Mehodes  
  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.         //------end Mehodes  
  18. }  
  19. // Onload event,when page load  
  20. window.onload = () => {  
  21.     var aemployee = new Employee();  
  22.     aemployee.FirstName = "Toufique";  
  23.     aemployee.LastName = "Rahman";  
  24.     var fullName = aemployee.GetFullName();  
  25.     var reverseName = aemployee.GetReverseName();  
  26.     document.getElementById('fulName').innerHTML = fullName;  
  27.     document.getElementById('reverseName').innerHTML = reverseName;  
  28. };  
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.  
  6. public GetFullName(): string {  
  7.     return this.FirstName + " " + this.LastName;  
  8. }  
  9. public GetReverseName(): string {  
  10.     var fullName = this.GetFullName();  
  11.     var reverse = '';  
  12.     for (var i = fullName.length - 1; i >= 0; i--) reverse += fullName[i];  
  13.     return reverse;  
  14. }  
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.  
  3. aemployee.FirstName = "Toufique";  
  4. 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 in variable.
  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. {  
  3.     public FirstName: string;  
  4.     public LastName: string;  
  5.     constructor(firstName: string, lastName: string) {  
  6.         this.FirstName = firstNmae;  
  7.         this.LastName = lastName;  
  8.     }  
  9.     public GetFullName(): string {  
  10.         return this.FirstName + "" + this.LastName;  
  11.     }  
  12. }  
Call Employee class

class

Let get the code explained.

Above, we see that there is a constructor which 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 constructor is in class with 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 type. This relationship is called IS-A Relationship.

Inheritance
Fig: Inheritance relationship between two class

Base Class

  1. class PermanentEmployee   
  2. {  
  3.     public FirstName: string;  
  4.     public LastName: string;  
  5.     constructor(firstName: string, lastName: string)   
  6.     {  
  7.         this.FirstName = firstName;  
  8.         this.LastName = lastName;  
  9.     }  
  10.     public GetFullName(): string   
  11.     {  
  12.         return this.FirstName + " " + this.LastName;  
  13.     }  
  14.     public GetReverseName(): string   
  15.     {  
  16.         var fullName = this.GetFullName();  
  17.         var reverse = '';  
  18.         for (var i = fullName.length - 1; i >= 0; i--) reverse += fullName[i];  
  19.         return reverse;  
  20.     }  
  21. }  
Sub Class
  1. class TemporaryEmployee extends PermanentEmployee   
  2. {  
  3.     public JobDuration: string;  
  4.     constructor(firstName: string, lastName: string) {  
  5.         super(firstName, lastName);  
  6.     }  
  7. }  
  8. var employeeObj = new TemporaryEmployee("Toufique""Rahman");  
  9. var fullName = employeeObj.GetFullName();  
  10. var reverseName = employeeObj.GetReverseName();  
Let’s explain the code.

Here, 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. {  
  3.     this.FirstName = firstName;  
  4.     this.LastName = lastName;  
  5. }  
Two methods- GetFullName,
  1. public GetFullName(): string {  
  2.     return this.FirstName + " " + this.LastName;  
  3. }  
and GetReverseName,
  1. public GetReverseName(): string   
  2. {  
  3.     var fullName = this.GetFullName();  
  4.     var reverse = '';  
  5.     for (var i = fullName.length - 1; i >= 0; i--) reverse += fullName[i];  
  6.     return reverse;  
  7. }  
Sub class is TemporaryEmployee.

class TemporaryEmployee extends PermanentEmployee {

Here, TemporaryEmployee class inherits PermanentEmployee class using extends keyword. Now, we can access PermanentEmployee.

Attribute

public JobDuration: string;

Constructor
  1. constructor(firstName: string, lastName: string) { super(firstName, lastName); }  
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 sub class (TemporaryEmployee). Initially, these were defined in base class (PermanentEmployee). Now, we can access these in sub class (TemporaryEmployee) also for IS-A Relationship.

Access Modifiers 
  • TypeScript has three type 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 "public access modifier" to all the class members (functions or properties), by default.

Public Access

If use public access modifier, the members (functions or properties) can be accessed anywhere in the code freely. Like, Base class or Sub Class.

Example

Lets get the code explanation.

  1. class SavingAccount   
  2. {  
  3.     public AccountNo: string;  
  4.     private Amount: number;  
  5.     constructor(accountNo: string) {  
  6.         this.AccountNo = accountNo;  
  7.     }  
  8.     public Deposit(amount: number): string {  
  9.         this.Amount = amount;  
  10.         return "Deposit Successfully.";  
  11.     }  
  12.     public withdraw(amount: number): string {  
  13.         this.Amount = amount;  
  14.         return "withdraw Successfully.";  
  15.     }  
  16.     public TotalAmount(): number {  
  17.         return this.Amount;  
  18.     }  
  19. }  
  20. var _savingAccount = new SavingAccount("sav0234232");  
  21. _savingAccount.Deposit(1000);  
  22. _savingAccount.withdraw(500);  
  23. _savingAccount.TotalAmount();  
All Public members in class have been called by object reference of SavingAccount class, and public members always call sub class.

Private Access

If we use private access modifier, the members can be accessed within self class by its other class members (functions) only.

Example


Let's get it in code.
  1. class SavingAccount   
  2. {  
  3.     public AccountNo: string;  
  4.     private Amount: number;  
  5.     constructor(accountNo: string) {  
  6.         this.AccountNo = accountNo;  
  7.     }  
  8.     public Deposit(amount: number): string {  
  9.         this.Amount = amount;  
  10.         return "Deposit Successfully.";  
  11.     }  
  12.     public withdraw(amount: number): string {  
  13.         this.Amount = amount;  
  14.         return "withdraw Successfully.";  
  15.     }  
  16.     public TotalAmount(): number {  
  17.         return this.Amount;  
  18.     }  
  19. }  
  20. var _savingAccount = new SavingAccount("sav0234232");  
When we call Amount properties which is private properties, we get error.

Access

In the above code, we can see that Amount property is used in TotalAmount Function which is in SavingAccount class. So, we can easily use this Amount property.

Protected Access

If we use protected access modifier, the members can be accessed within sub class. 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 protected member of this class by using this class’s object, we get error.

error

Protected is like private.

Sub Class
  1. class SavingAccount extends Account {  
  2.     constructor(accountNo: string) {  
  3.             super(accountNo);  
  4.         }  
  5.         // Amount propertices is a protected which is base class  
  6.     public TotalAmount(): number {  
  7.         return this.Amount;  
  8.     }  
  9. }  
  10. var _savingAccount = new SavingAccount("Sav-43434");  
  11. _savingAccount.Deposit(1000);  
  12. _savingAccount.withdraw(500);  
In the above code, we can see that Amount property is used in TotalAmount function which is protected and exists in base class. From the above code, we know that protected member is used within Sub class, 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 object; that time, we use Static.

Example
  1. class Calculator   
  2. {  
  3.     public static FirstNumber: number;  
  4.     public static SecondNumber: number;  
  5.     public static addTowNumber(): number {  
  6.         return this.FirstNumber + this.SecondNumber;  
  7.     }  
  8. }  
  9. Calculator.FirstNumber = 10;  
  10. Calculator.SecondNumber = 30;  
  11. 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 of 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 Class and Method are ready. We just call and we will implement this method by itself. Method’s name will remain same in 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 method name and signature.

Interface Implemented
  1. class Employee implements iGenericFactory {  
  2.     public Save(): void {  
  3.         // Here Save code  
  4.     }  
  5.     public Update(): void {  
  6.         // Here Update code  
  7.     }  
  8.     public delete(): void {  
  9.         // Here Delete code  
  10.     }  
  11. }  
Note: 
  • When we implement the interface, then we must use implementation keyword.
  • All Methods will be implemented.

Happy Coding.