Click here to Skip to main content
15,881,172 members
Articles / Programming Languages / Typescript

Quick Reference for Typescript

Rate me:
Please Sign up or sign in to vote.
4.93/5 (12 votes)
20 Sep 2016CPOL9 min read 29.7K   7   6
In this article We will learn about TypeScript

Table of Contents                                                                                                                       

  1. What is Typescript
  2. Data Types
  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 TypeScripit:

TypeScript is Superset of JavaScript which is optional static typing and Class based object oriented programing Language. There are object oriented programing features like Class, Constructor, Object, Interface and always support primate data type. OOP Concept may be implemented in this Language .TypeScript’s code is more readable then JavasScript and It is open source and free.it created by Microsoft and announced 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

ChooseTemplate

Once click ok button, a project with need typescript's reference  will be created .

projectst

We can see that above picture app.css file it's css file,you can keep your css style's code in this file and we see app.ts, it's a typescript file, ts extension means typescript file,you can always keep your typescript's code in ts file.

Create ts file

Right click on your project >>click add>>click Javascript File and give named "Welcome.ts" and once click ok Button.Bellow is the following code.

// Class name welcome
class welcome { 
    element: HTMLElement;
     // constructor
    constructor(element: HTMLElement) {
        this.element = element;
        this.element.innerHTML= "Welcome To TypeScript";
    }
}
 // window onload event, when page open then call this onload event 
window.onload = () => {
    // get html divcontent 
    var elh = document.getElementById('divcontent'); 
    // create new object and call constructor with elh paramitter
    var _welcomeobj = new welcome(elh);    
};

Let’s get explained about Welcome.ts:

We have created Welcome class. There are a element properties and  a constructor which take a parameter this parameter's type is HTMLElement. When we will create instance of welcome class then automatic call constructor. We have  just given div id which is index page. We Know that how to get div id using javascript. For catch div id we have used document.getElementById."Welcome To TypeScript" has been assigned  within constructor.

Create Index Page Now we will create Index.html page for show our result on browser.Bellow is the following code.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>My Fisrt TypeScript's Application</title>
    <link rel="stylesheet" href="app.css" type="text/css" />
    <script src="Welcome.js"></script>
</head>
<body>
    <h1>My Fisrt TypeScript's Application</h1>

    <div id="divcontent"></div>
</body>
</html>

We have just add Welcome.js reference on index.html page. Because we have used Welcome.js for our coding.it is our Typescript file.

Finally Output:

hellowresult

Data Types

Background: We know that every programming language have basically two data type once is primitive data type and other is costom data type .But today we will discuss about Primitive data type like Boolean, Number, String, Any, Array, Enum

syntax:

Syntax

Create ts file:

Right click on your project >>click add>>click Javascript File and give named “DataType.ts” and once click ok Button.Bellow is the following code.

class DataType {

    // boolean Type
    Status: boolean = true; // output ture
    // number Type
    Amount: number = 100; // output 100
    // number always support like decimal,hex,binary,octal
    Price: number = 50.5; // output 50.5
    // string Type
    Subject: string = "TypeScript"; // TypeScript
    // any like dynamic type 
    Value: any = 5;

    // we know that when class object will be Created then automatic call constructor 
    constructor() {
        console.log(this.Status);
        console.log(this.Amount);
        console.log(this.Price);
        console.log(this.Subject);
        console.log(this.Value);
    }
}
window.onload = () => {
    // Create class object 
    var val = new DataType();
}

Let's get explaine about data types Boolean:

// boolean Type
 Status: boolean = true; // output ture

We can see that above line,Status variable has took  bool type data.if we keep string or number type data in Status variable then will show error.

String:

Subject: string = "TypeScript"; //output is TypeScript
Name:string='Mamun'; //output is Mamun

String is textual data.Double quotes (") or single quotes(') is used in TypeScript. String data type will shown error without double quotes or single quotes.

1. Number: Number is very interesting data type in Type Script. Number can take like : 1. Decimal

decimal: number = 10;

2. Hexadecimal

hex: number = 0xf00d;

3. Binary

binary: number = 0b1111;

4. Octal

octal: number = 0o744;

Output:

DataTypeOutput

Enum

Enum is helpful addition to the standard set of datatypes from JavaScript. data is stored in enum. Enum's data do not modify without enum block. Enums begin numbering their members starting at 0, By default. but it may be changed by manually.

Let’s get started:  

Create ts file: Right click on your project >>click add>>click Javascript File and give named “SalaryCal.ts” and once click ok Button.Bellow is the following code

enum SalaryHead {
    // these are %
    Basic = 50,
    Houserent = 30,
    Medical = 10,
    Conveyance = 10
}
class SalaryCal {
    // let gross salary is 50000,Gross Salary will be given from IU in real wrold 
    Gross: number = 50000;
    // Calculate Basic from gross slary
    BasicSalary: number = (this.Gross * SalaryHead.Basic) / 100;
    // Calculate House Rent from gross slary
    Houserent: number = (this.Gross * SalaryHead.Houserent) / 100;
    // Calculate Medical from gross slary
    Medical: number = (this.Gross * SalaryHead.Medical) / 100;
    // Calculate Conveyance from gross slary
    Conveyance: number = (this.Gross * SalaryHead.Conveyance) / 100;

    // we can not modify enum valu without enum block
   // SalaryHead.Basic=60;

    constructor() {
        // Now we will check sum of salary head and gross are equal.
        if ((this.BasicSalary + this.Houserent + this.Medical + this.Conveyance) == this.Gross) {
            console.log("Both are equal");
        }
        else {
            console.log("Both are not equal");
        }
    }   
}

window.onload = () => {
    // Create class object 
    var val = new SalaryCal();
}

Let's get explain about enum:

Above we can see that we have declared enum which name is "SalaryHead" . There are assigned some enum's property. When it needs to use in our application then just call enum. But enum's property never change without enum scope. Now if enum's property is called then we get assigned value. 

enum Status {
    IsDelete,
    IsPending,
    IsApprove
};

Above is Status enum which is contained three status like IsDelete, IsPending and IsApprove.

Call: Status[0] 

Output: IsDelete

Function

What is Function: Group of statements perform together which solve a specific task. Every function should be solved a single task.There are some region why we use function like are:

  • Organization
  • Reusability
  • Testing
  • Extensibility
  • Abstraction

Function can be created both as a named function or as a anonymous function in Type Script.

Named function without parameter :

function GetFullName(): string
{
    return "Toufique Rahman Tshovon";
}
var Name = GetFullName();
console.log(Name);

let's get explain about code GetFullName is function name which did not use any parameter and return type string. function and return are keyword. return keyword return value.

Output: Toufique Rahman Tshovon

Named function with parameter:

function GetFullName(firstName: string, lastName: string): string {
    return firstName + " " + lastName;
}
var Name = GetFullName("Shamim", "Uddin");
console.log(Name);

let's get explain about code GetFullName is function name which have taken two parameter one is firstName another one is lastName both are string type. firstName and lastName have been concatenated.

Output: Shamim uddin

Anonymous function without parameter:

var Name = function (): string {
    return "Toufique Rahman Tshovon";
}
console.log(Name());

let's get explain about code There are no method name. But Name variable hold function's perform which has no parameter.

Output: Toufique Rahman Tshovon

Anonymous function with parameter:

var Name = function (firstName: string, lastName: string): string {
    return firstName + " " + lastName;
}
console.log(Name("Shamim", "Uddin"));

let's get explain about code There are no method name. But Name variable hold function's perform which have two parameter One is firstName another one is lastName both are string type. firstName and lastName have been concatenated.

Default Arguments:

function add(firstnumber: number, secondNumber: number=10): number {
    return firstnumber + secondNumber;
}
console.log(add(10));

Output: 20

let's get explain 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

function add(firstnumber: number, secondNumber: number=10): number {
    return firstnumber + secondNumber;
}
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  Bellow is the following code:

function Add(firstNumber: number, secondNumber: number)
function Add(firstNumber: number, secondNumber: number, thirdNumber:number)
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;
    }
    return result;
}
console.log(Add(1, 2));
console.log(Add(1, 2, 2));
console.log(Add(1, 2, 2, 5));

Let's get explain about code:

function Add(firstNumber: number, secondNumber: number)

Add is a function which have two parameters.

function Add(firstNumber: number, secondNumber: number, thirdNumber)

Add is a function which have three parameters.

function Add(firstNumber: number, secondNumber: number, thirdNumber, forthNumber: number);

Add is a function which have four parameters.

Bellow, There are three methods which  are same name but number of parameter are different.

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;
    }
    return result;
}

Above we have implemented our method . result is variable which have assigned by default 0 and used if else statement . Parameters wise methods call.

Class & Object

A class is a Template which contains attributes and methods.It is one kind of costum data type. Class is used to

create unlimited Objects.

Fig: Class structure

ClassStructure

There are three sections in above fig.

Class Name: You have to give name of class.Ex- Employee.

Attributes: You have to define class's attributes . let class name Employee . you have to brainstorming, what will be attributes? Ex-1. FirstName. 2. LastName.

Method: You have to define what kind of task will you do using this class. 

Ex-1. GetFullName() 2. GetReverseName()

Object: Object is an individual instance which create from specific class.

Fig: Multiple object from class

Object

We can see above picture. One Employee class and four objects of employee class.Object may be created unlimited that mean  when you need to create object then you can create object Let's go to code.

class Employee {
    // -----start attributes
    public FirstName: string;
    public LastName: string;
     // -----end attributes

    //------start Mehodes
    public GetFullName(): string
    {
        return this.FirstName + " " + this.LastName;
    }
 
    public GetReverseName(): string {
        var fullName = this.GetFullName();        
        var reverse = '';
        for (var i = fullName.length - 1; i >= 0; i--)
            reverse += fullName[i];
        return reverse;
    }
    //------end Mehodes
}
// Onload event,when page load
window.onload = () => {
    var aemployee = new Employee();
    aemployee.FirstName = "Toufique";
    aemployee.LastName = "Rahman";
    var fullName = aemployee.GetFullName();
    var reverseName = aemployee.GetReverseName();
    document.getElementById('fulName').innerHTML = fullName;
    document.getElementById('reverseName').innerHTML = reverseName;
};

Let’s get explain about code:

class Employee

Class Name Employee

public FirstName: string;
public LastName: string;

Both lines are class attributes.

public GetFullName(): string
  {
      return this.FirstName + " " + this.LastName;
  }

  public GetReverseName(): string {
      var fullName = this.GetFullName();
      var reverse = '';
      for (var i = fullName.length - 1; i >= 0; i--)
          reverse += fullName[i];
      return reverse;
  }

There are two method in above code one is GetFullName() and other one is Ger ReverseName().

var aemployee = new Employee();

Object has created which name is aemployee.

aemployee.FirstName = "Toufique";
aemployee.LastName = "Rahman";

Class's attributes have assigned which are FirstName and LastName

var fullName = aemployee.GetFullName();
var reverseName = aemployee.GetReverseName();

Two Methods have called and kept in variable

document.getElementById('fulName').innerHTML = fullName;
document.getElementById('reverseName').innerHTML = reverseName;

Those are simple javascript code,get html tag and assign value.

Constructor

Constructor is one kind of special method. It is called when create object of class by default.

Example: Bellow is the following code of Employee class

class Employee {
    public FirstName: string;
    public LastName: string;

    constructor(firstName: string, lastName: string) {
        this.FirstName = firstNmae;
        this.LastName = lastName;
    }

    public GetFullName(): string {
        return this.FirstName + "" + this.LastName;
    }
}

Call Employee class:

Fig: Create Object

Untitled

 

Let get code explain:

Above code we see that there is a constructor which have two parameter.Once is firstName and other once is lastName. Both parameters are assigned FirstName and LastName which are attributes of Employee class. Created Object of Employee class:

var aemployee = new Employee("Toufique", "Rahman");

Note:

  • Multiple constructor implementations are not allowed.
  • If constructor is in class with parameter then without pass argument,Object create impossible.

Inheritance

Inheritance is object oriented programming language's one kind of patter which makes relationship between different class but common type. This relationship is called IS-A Relationship.

Fig: Inheritance relationship between tow class

Inheritance

Base Class:

class PermanentEmployee {
     public FirstName: string;
     public LastName: string;

     constructor(firstName: string, lastName: string) {
         this.FirstName = firstName;
         this.LastName = lastName;
     }

     public GetFullName(): string {
         return this.FirstName + " " + this.LastName;
     }

     public GetReverseName(): string {
         var fullName = this.GetFullName();
         var reverse = '';
         for (var i = fullName.length - 1; i >= 0; i--)
             reverse += fullName[i];
         return reverse;
     }
}

Sub Class:

class TemporaryEmployee extends PermanentEmployee {

    public JobDuration: string;

    constructor(firstName: string, lastName: string) { super(firstName, lastName); }

}
var employeeObj = new TemporaryEmployee("Toufique", "Rahman");
var fullName = employeeObj.GetFullName();
var reverseName = employeeObj.GetReverseName();

Let’s get explain about code:

Here, Base class is PermanentEmployee.

class PermanentEmployee {

Attributes

public FirstName: string;
public LastName: string;

Constructor have two parameters.Once is firstName and Other once is lastName. Both are assigned to attributes.

constructor(firstName: string, lastName: string) {
         this.FirstName = firstName;
         this.LastName = lastName;
     }

Two method, Once is GetFullName

public GetFullName(): string {
      return this.FirstName + " " + this.LastName;
  }

Other once is GetReverseName

public GetReverseName(): string {
         var fullName = this.GetFullName();
         var reverse = '';
         for (var i = fullName.length - 1; i >= 0; i--)
             reverse += fullName[i];
         return reverse;
     }

Sub class is TemporaryEmployee.

class TemporaryEmployee extends PermanentEmployee {

Here TemporaryEmployee class  Inhered PermanentEmployee class using extends keyword.Now we can access PermanentEmployee. Attribute

public JobDuration: string;

Constructor

constructor(firstName: string, lastName: string) { super(firstName, lastName); }

Constructor taken tow parameters.  Parameters values are assigned Basic class's constructor using super keyword. TemporaryEmployee class's object created

var employeeObj = new TemporaryEmployee("Toufique", "Rahman");
var fullName = employeeObj.GetFullName();
var reverseName = employeeObj.GetReverseName();

created object employeeobj then passing two attributes for constructor. Interesting think here, We can access GetFullName and GetReverseName in sub class (TemporaryEmployee). These were base class(PermanentEmployee).Now we can access these in sub class (TemporaryEmployee)  for IS-A Relationship.

Access Modifiers

  • TypeScript have three type of access modifier which are public, private and protected.
  • Access Modifiers prevent to miss use of class members(functions and properties)
  • If no use any acess modifier,TypeScript set public access modifier to all class members(functions or properties) by defult

Public Access:

If use public access modifier with member of class(function or properties), Those members can be accessed anywhere in code freely.Like Base class or Sub Class.

Example:

Lets get below code snippet Explanation:

class SavingAccount {

    public AccountNo: string;
    private Amount: number;

    constructor(accountNo: string) {
        this.AccountNo = accountNo;
    }
    public Deposit(amount: number): string {
        this.Amount = amount;
        return "Deposit Successfully.";
    }
    public withdraw(amount: number): string {
         this.Amount = amount;
        return "withdraw Successfully.";
    }
    public TotalAmount(): number {
        return this.Amount;
    }
}

var _savingAccount = new SavingAccount("sav0234232");
_savingAccount.Deposit(1000);
_savingAccount.withdraw(500);
_savingAccount.TotalAmount();

All Public Member in class(functions and properties) have been called by object reference of SavingAccount class and public  member always call sub class.

Private Access: If use private access modifier with member of class(function or properties), Those members can be accessed within self class by its other class members (functions) only.

Example:

Lets get below code snippet Explanation:

class SavingAccount {

    public AccountNo: string;
    private Amount: number;

    constructor(accountNo: string) {
        this.AccountNo = accountNo;
    }
    public Deposit(amount: number): string {
        this.Amount = amount;
        return "Deposit Successfully.";
    }
    public withdraw(amount: number): string {
         this.Amount = amount;
        return "withdraw Successfully.";
    }
    public TotalAmount(): number {
        return this.Amount;
    }
}

var _savingAccount = new SavingAccount("sav0234232");

When we call Amount properties which is private properties. Then we got error

privaterror

Above code we can see that Amount properties is used in TotalAmount Function which is in SavingAccount class. So we can easily use this Amount Properties.

protected Access: If use protected access modifier with member of class (function or properties), Those members can be accessed within sub class. Otherwise this access modifier can not be accessed.

Example: Base Class

class Account {

    public AccountNo: string;
    protected Amount: number;

    constructor(accountNo: string) {
        this.AccountNo = accountNo;
    }
    public Deposit(amount: number): string {
        this.Amount = amount;
        return "Deposit Successfully.";
    }
    public withdraw(amount: number): string {
         this.Amount = amount;
        return "withdraw Successfully.";
    }
    protected TotalAmount(): number {
        return this.Amount;
    }
}

When we call Protected member of this class by using this class's object then we got error

222222

Protected is like private.

Sub Class:

class SavingAccount extends Account
{
    constructor(accountNo: string) { super(accountNo); }

    // Amount propertices is a protected which is base class
    public TotalAmount(): number {
        return this.Amount; 
    }
}

var _savingAccount = new SavingAccount("Sav-43434");
_savingAccount.Deposit(1000);
_savingAccount.withdraw(500);
_savingAccount.TotalAmount();

Above code we can see that Amount properties is using in TotalAmount function which is proptected and exist base class. From Above code we know that protected member is used within Sub class.Other wise we can not use this.

Static Functions & Properties

Static functions and properties can only be called by their class reference and cannot be called by an object reference.Sometime we need to void unnecessary created object that time we use Static.

Example:

class Calculator {

    public static FirstNumber: number;
    public static SecondNumber: number;

    public static addTowNumber(): number {
        return this.FirstNumber + this.SecondNumber;
    }
}

Calculator.FirstNumber = 10;
Calculator.SecondNumber = 30;
Calculator.addTowNumber()

Lets get code Explain:

Above code There are two static  properties and one static function .When those properties and functions are called then do not need created object. Those are called by Class Name

Like:

Calculator.FirstNumber = 10;
Calculator.SecondNumber = 30;
Calculator.addTowNumber()

Interface

Interface is Object oriented syntax which is used  manage application beauty. That means that Class and Method is ready. We just call and we will implement this method by self . Method's name will be same in whole application. Example: Interface class

interface iGenericFactory {

    Save(): void;
    Update(): void;
    delete(): void
}

Here there are no methods implementation. We can see that just method name and signature. Interface Implemented

class Employee implements iGenericFactory 
{
    public Save(): void {
        // Here Save code
    }
    public Update(): void {
        // Here Update code
    }
    public delete(): void {
        // Here Delete code
    }
 
  }

Note:

  • When we implement interface then must be used implements keyword.
  • All Methods will be implement.

Happy Coding :) 

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Amber Software Solution Ltd.
Bangladesh Bangladesh
Hi, I am Shamim Uddin.Working with Microsoft Technologies.

Comments and Discussions

 
Questionformat Pin
Nelek3-Feb-19 2:21
protectorNelek3-Feb-19 2:21 
GeneralMy vote of 5 Pin
Farhad Reza10-Dec-16 7:28
Farhad Reza10-Dec-16 7:28 
QuestionOne small typo Pin
DalalV19-Sep-16 18:57
DalalV19-Sep-16 18:57 
QuestionGood work Pin
Prabu ram31-Aug-16 20:20
Prabu ram31-Aug-16 20:20 
AnswerRe: Good work Pin
Shamim Uddin31-Aug-16 20:27
professionalShamim Uddin31-Aug-16 20:27 
GeneralMy vote of 5 Pin
Shashangka Shekhar31-Aug-16 19:45
professionalShashangka Shekhar31-Aug-16 19:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.