Table of Contents
- What is TypeScript
- Data Type
- Enum
- Function
- Function Overloading
- Class & Object
- Constructor
- Inheritance
- Access Modifiers
- Static Functions & Properties
- 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.
Once the click OK button, a project with need TypeScript’s reference will be created.
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.
- class welcome {
- element: HTMLElement;
- constructor(element: HTMLElement) {
- this.element = element;
- this.element.innerHTML = "Welcome To TypeScript";
- }
- }
- window.onload = () => {
- var elh = document.getElementById('divcontent');
- var _welcomeobj = new welcome(elh);
- };
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.
- < !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 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.
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.
Create a ts file
- class DataType {
- Status: boolean = true;
- Amount: number = 100;
- Price: number = 50.5;
- Subject: string = "TypeScript";
- Value: any = 5;
- constructor() {
- console.log(this.Status);
- console.log(this.Amount);
- console.log(this.Price);
- console.log(this.Subject);
- console.log(this.Value);
- }
- }
- window.onload = () => {
- var val = new DataType();
- }
Let’s explain the data types.
Boolean
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
- Subject: string = "TypeScript";
- 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:
- Decimal
decimal: number = 10;
- Hexadecimal
hex: number = 0xf00d;
- Binary
binary: number = 001101;
- 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
- enum SalaryHead {
- Basic = 50, Houserent = 30, Medical = 10, Conveyance = 10
- }
- class SalaryCal {
- Gross: number = 50000;
- BasicSalary: number = (this.Gross * SalaryHead.Basic) / 100;
- Houserent: number = (this.Gross * SalaryHead.Houserent) / 100;
- Medical: number = (this.Gross * SalaryHead.Medical) / 100;
- Conveyance: number = (this.Gross * SalaryHead.Conveyance) / 100;
- constructor() {
- 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 = () => {
- var val = new SalaryCal();
- }
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
- enum Status {
- IsDelete,
- IsPending,
- IsApprove
- };
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 -
- function GetFullName(): string {
- return "Toufique Rahman Tshovon";
- }
- var Name = GetFullName();
- 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 -
- function GetFullName(firstName: string, lastName: string): string {
- return firstName + " " + lastName;
- }
- var Name = GetFullName("Shamim", "Uddin");
- 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-
- var Name = function(): string {
- return "Toufique Rahman Tshovon";
- }
- 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 -
- var Name = function(firstName: string, lastName: string): string {
- return firstName + " " + lastName;
- }
- 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
- function add(firstnumber: number, secondNumber: number = 10): number {
- return firstnumber + secondNumber;
- }
- 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,
- 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.
Given below is the 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 explain the code,
- function Add(firstNumber: number, secondNumber: number)
Add is a function with two parameters.
- function Add(firstNumber: number, secondNumber: number, thirdNumber: number)
Add is a function with three parameters.
- 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.
- 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. 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.
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.
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.
- class Employee {
- public FirstName: string;
- public LastName: string;
- 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;
- }
- }
- 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 explain the 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 methods in the above code - GetFullName() and Ger ReverseName().
- var aemployee = new Employee();
- Object has created which name is aemployee.aemployee.FirstName = "Toufique";
- aemployee.LastName = "Rahman";
Class’s attributes have been assigned as FirstName and LastName.
- var fullName = aemployee.GetFullName();
- var reverseName = aemployee.GetReverseName();
Two methods have been called and kept invariable.
- document.getElementById('fulName').innerHTML = fullName;
- 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.
- 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
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.
- 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.
Fig: Inheritance relationship between two class
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 explain the code.
Here, the Base class is PermanentEmployee.
- class PermanentEmployee {
Attributes
- public FirstName: string;
- public LastName: string;
Constructor has two parameters, firstName, and lastName. Both are assigned to attributes.
- constructor(firstName: string, lastName: string) {
- this.FirstName = firstName;
- this.LastName = lastName;
- }
Two methods- GetFullName,
- public GetFullName(): string {
- return this.FirstName + " " + this.LastName;
- }
and 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, the TemporaryEmployee class inherits the PermanentEmployee class using extends keyword. Now, we can access PermanentEmployee.
Attribute
public JobDuration: string;
Constructor
- 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.
- var employeeObj = new TemporaryEmployee("Toufique", "Rahman");
- var fullName = employeeObj.GetFullName();
- 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.
- 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 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.
- 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 are private properties, we get the error.
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
- 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 a protected members of this class by using this class’s object, we get an error.
Protected is like private.
Sub Class
- class SavingAccount extends Account {
- constructor(accountNo: string) {
- super(accountNo);
- }
- public TotalAmount(): number {
- return this.Amount;
- }
- }
- var _savingAccount = new SavingAccount("Sav-43434");
- _savingAccount.Deposit(1000);
- _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
- 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()
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,
- Calculator.FirstNumber = 10;
- Calculator.SecondNumber = 30;
- 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
- interface iGenericFactory {
- Save(): void;
- Update(): void;
- delete(): void
- }
Here, there are no method implementations. We can see only the method name and signature.
Interface Implemented
- class Employee implements iGenericFactory {
- public Save(): void {}
- public Update(): void {}
- public delete(): void {}
- }
Note:
- When we implement the interface, then we must use the implementation keyword.
- All Methods will be implemented.
Happy Coding.