Please enable Javascript to correctly display the contents on Dot Net Tricks!

Classes

Posted On : 09 Mar 2017
Updated On : 01 Jan 0001
Total Views : 511

Classes

ECMAScript 6 or ES6 provides class type to build JavaScript application by using object-oriented class-based approach. TypeScript extends ES6 class type with typed members and access modifiers like classes in C# or Java programming languages.

In TypeScript, you can compile class type down to JavaScript standard ES5 that will work across all major browsers and platforms.

class.ts

class Student {
 private rollNo: number;
 private name: string;

 constructor(_rollNo: number, _name: string) {
 this.rollNo = _rollNo;
 this.name = _name;
 }
 showDetails() { //public : by default
 console.log(this.rollNo + " : " + this.name);
 }
}

let s1 = new Student(1, "Shailendra Chauhan");
s1.showDetails(); //1 : Shailendra Chauhan

let s2 = new Student(2, "kanishk Puri");
s2.showDetails(); //2 : kanishk Puri

The compiled JavaScript (ES5) code for the above TypeScript code is give below:

class.js

var Student = (function () {
 function Student(_rollNo, _name) {
 this.rollNo = _rollNo;
 this.name = _name;
 }
 Student.prototype.showDetails = function () {
 console.log(this.rollNo + " : " + this.name);
 };
 return Student;
}());
var s1 = new Student(1, "Shailendra Chauhan");
s1.showDetails();

var s2 = new Student(2, "kanishk Puri");
s2.showDetails();

Constructors

Just like object oriented programming languages C# or Java, TypeScript class type supports two types of constructors - default constructor and parameterized constructor.

Unlike C# or Java, in typescript constructor, you can make public, private or protected instance members of a class.

constructor.ts

class Customer {
 //instance members with access modifiers
 constructor(private id:number, public name:string, protected address:string) { }
 showDetails() {
 console.log(this.id + " : " + this.name + " : " + this.address);
 }
}

let c1 = new Customer(1, "Shailendra Chauhan", "Noida");
c1.showDetails(); //1 : Shailendra Chauhan : Noida

The compiled JavaScript (ES5) code for the above TypeScript code is give below:

constructor.js

var Customer = (function () {
 //instance members with access modifiers
 function Customer(id, name, address) {
 this.id = id;
 this.name = name;
 this.address = address;
 }
 Customer.prototype.showDetails = function () {
 console.log(this.id + " : " + this.name + " : " + this.address);
 };
 return Customer;
}());
var c1 = new Customer(1, "Shailendra Chauhan", "Noida");
c1.showDetails();

Instance and Static Members

TypeScript class members are either instance members or static members.

Instance members are members of the class type and its instance. Within constructors, member functions and accessors, this represents to the instance of the class.

Static members are declared using the static keyword and are the members of constructor function type. Within static functions and static accessors, this represents to the constructor function type.

Static members are accessible by using the class name only, not by using the class instance. Inside static method, you can access only static members.

members.ts

class Booklist {
 //instance members
 private books: string[] = []; //instance property or instance member
 constructor(public name: string) {
 }
 addBook(book: string) { //member function or instance member function
 if (this.books.length >= Booklist.maxBookCount) {
 throw new Error('Booklist is full');
 }
 else {
 this.books.push(book);
 Booklist.totalBooksCount++;
 }
 }
 //static members
 static totalBooksCount: number = 0;
 static maxBookCount: number = 20;
 static totalBooks() { //static methods
 return Booklist.totalBooksCount;
 }
}

let booklist = new Booklist('My Book List');

// acessing instance members using class instance
let listName = booklist.name;
booklist.addBook("Gurukulsight - TypeScript Training Book");
booklist.addBook("Gurukulsight - Angular2 Training Book");

// accessing static members using class name
let maxBooks = Booklist.maxBookCount; //20
let totalBooks = Booklist.totalBooks(); //2

console.log(maxBooks);
console.log(totalBooks);

The compiled JavaScript (ES5) code for the above TypeScript code is give below:

members.js

var Booklist = (function () {
 function Booklist(name) {
 this.name = name;
 this.books = [];
 }
 Booklist.prototype.addBook = function (book) {
 if (this.books.length >= Booklist.maxBookCount) {
 throw new Error('Booklist is full');
 }
 else {
 this.books.push(book);
 Booklist.totalBooksCount++;
 }
 };
 Booklist.totalBooks = function () {
 return Booklist.totalBooksCount;
 };
 return Booklist;
}());

Booklist.totalBooksCount = 0;
Booklist.maxBookCount = 20;
var booklist = new Booklist('My Book List');

var listName = booklist.name;
booklist.addBook("Gurukulsight - TypeScript Training Book");
booklist.addBook("Gurukulsight - Angular2 Training Book");

var maxBooks = Booklist.maxBookCount;
var totalBooks = Booklist.totalBooks();
console.log(maxBooks);
console.log(totalBooks);

Access Modifiers

TypeScript supports three access modifiers - public, private, and protected.

  1. Public - By default, members (properties and methods) of TypeScript class are public - so you don’t need to prefix members with the public keyword. Public members are accessible everywhere without restrictions

  2. Private - A private member cannot be accessed outside of its containing class. Private members can be accessed only within the class.

  3. Protected - A protected member cannot be accessed outside of its containing class. Protected members can be accessed only within the class and by the instance of its sub/child class.

In compiled JavaScript code, there will be no such types of restriction on the members.

accessmodifiers.ts

class Foo {
 private x: number;
 protected y: number;
 public z: number;
 saveData(foo: Foo): void {
 this.x = 1; // ok
 this.y = 1; // ok
 this.z = 1; // ok

 foo.x = 1; // ok 
 foo.y = 1; // ok 
 foo.z = 1; // ok
 }
}

class Bar extends Foo {
 getData(foo: Foo, bar: Bar) {
 this.y = 1; // ok
 this.z = 1; // ok

 bar.y = 1; // ok
 bar.z = 1; // ok
 foo.z = 1; // ok

 foo.x = 1; // Error, x only accessible within A 
 bar.x = 1; // Error, x only accessible within A 
 bar.y = 1; // Error, y only accessible through instance of B 
 }
}

The compiled JavaScript (ES5) code for the above TypeScript code is give below:

accessmodifiers.js

var Foo = (function () {
 function Foo() {
 }
 Foo.prototype.saveData = function (foo) {
 this.x = 1; 
 this.y = 1; 
 this.z = 1;
 foo.x = 1; 
 foo.y = 1; 
 foo.z = 1;
 };
 return Foo;
}());
var Bar = (function (_super) {
 __extends(Bar, _super);
 function Bar() {
 return _super.apply(this, arguments) || this;
 }
 Bar.prototype.getData = function (foo, bar) {
 this.y = 1; 
 this.z = 1;
 bar.y = 1; 
 bar.z = 1;
 foo.z = 1;
 foo.x = 1;
 bar.x = 1; 
 bar.y = 1; 
 };
 return Bar;
}(Foo));

Readonly Modifiers

TypeScript supports readonly modifiers on property level by using the readonly keyword. The Readonly properties must be initialized at their declaration or in the constructor.

readonly.ts

class Company {
 readonly country: string = "India";
 readonly name: string;

 constructor(_name: string) {
 this.name = _name;
 }
 showDetails() {
 console.log(this.name + " : " + this.country);
 }
}

let c1 = new Company("Dot Net Tricks Innovation");
c1.showDetails(); // Dot Net Tricks Innovation : India

c1.name = "TCS"; //Error, name can be initialized only within constructor

The compiled JavaScript (ES5) code for the above TypeScript code is give below:

readonly.js

var Company = (function () {
 function Company(_name) {
 this.country = "India";
 this.name = _name;
 }
 Company.prototype.showDetails = function () {
 console.log(this.name + " : " + this.country);
 };
 return Company;
}());
var c1 = new Company("Dot Net Tricks Innovation");
c1.showDetails();
c1.name = "TCS";

Accessors

Just like C# properties accessors, TypeScript supports get/set accessors to access and to set the value to a member of an object. This way give us control over how a member of an object is accessed and set.

accessors.ts

class Employee {
 private passcode: string;
 private _fullName: string;

 constructor(_passcode?: string) {
 this.passcode = _passcode;
 }
 get fullName(): string { //accessing value
 return this._fullName;
 }
 set fullName(newName: string) { //setting value
 if (this.passcode == "secret_passcode") {
 this._fullName = newName;
 }
 else {
 console.log("Error: Unauthorized update of employee!");
 }
 }
}

let e1 = new Employee("secret_passcode");
e1.fullName = "Shailendra Chauhan";
if (e1.fullName) {
 console.log(e1.fullName);
}

let e2 = new Employee();
e2.fullName = "Kanishk Puri"; //Error: Unauthorized update of employee 
if (e2.fullName) {
 console.log(e1.fullName);
}

The compiled JavaScript (ES5) code for the above TypeScript code is give below:

accessors.js

var Employee = (function () {
 function Employee(_passcode) {
 this.passcode = _passcode;
 }
 Object.defineProperty(Employee.prototype, "fullName", {
 get: function () {
 return this._fullName;
 },
 set: function (newName) {
 if (this.passcode == "secret_passcode") {
 this._fullName = newName;
 }
 else {
 console.log("Error: Unauthorized update of employee!");
 }
 },
 enumerable: true,
 configurable: true
 });
 return Employee;
}());
var e1 = new Employee("secret_passcode");
e1.fullName = "Shailendra Chauhan";
if (e1.fullName) {
 console.log(e1.fullName);
}
var e2 = new Employee();
e2.fullName = "Kanishk Puri"; //Error: Unauthorized update of employee 
if (e2.fullName) {
 console.log(e1.fullName);
}

Inheritance

Inheritance is an important aspect of object oriented programming languages like C# and Java. Inheritance is a mechanism of acquiring the features and behaviors of a class by another class. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived/child class. Further, in child class you can override or modify the behaviors of its parent class and also can add new one.

Traditional JavaScript uses functions and prototype-based inheritance but TypeScript supports object-oriented class-based inheritance. Hence, in TypeScript you can extend the features and behaviors of an existing class into new one through the extends keyword.

Like C# and Java languages, TypeScript supports only single inheritance and multi-level inheritance. It doesn’t support multiple and hybrid inheritance.

inheritance.ts

class Person {
 private firstName: string;
 private lastName: string;
 constructor(_firstName: string, _lastName: string) {
 this.firstName = _firstName;
 this.lastName = _lastName;
 }
 fullName(): string {
 return this.firstName + " " + this.lastName;
 }
}

class Employee extends Person {
 id: number;
 constructor(_id: number, _firstName: string, _lastName: string) {
 //calling parent class constructor
 super(_firstName, _lastName);

 this.id = _id;
 }
 showDetails(): void {
 //calling parent class method
 console.log(this.id + " : " + this.fullName());
 }
}

let e1 = new Employee(1, "Shailendra", "Chauhan");
e1.showDetails(); //1 : Shailendra Chauhan

The compiled JavaScript (ES5) code for the above TypeScript code is give below:

inheritance.js

var __extends = (this && this.__extends) || function (d, b) {
 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
 function __() { this.constructor = d; }
 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Person = (function () {
 function Person(_firstName, _lastName) {
 this.firstName = _firstName;
 this.lastName = _lastName;
 }
 Person.prototype.fullName = function () {
 return this.firstName + " " + this.lastName;
 };
 return Person;
}());
var Employee = (function (_super) {
 __extends(Employee, _super);
 function Employee(_id, _firstName, _lastName) {
 var _this = 
 _super.call(this, _firstName, _lastName) || this;
 _this.id = _id;
 return _this;
 }
 Employee.prototype.showDetails = function () {
 console.log(this.id + " : " + this.fullName());
 };
 return Employee;
}(Person));
var e1 = new Employee(1, "Shailendra", "Chauhan");
e1.showDetails();

Abstract Class

An Abstract class is a special type of class which cannot be instantiated and acts as a base class for other classes. Abstract class members marked as abstract must be implemented by derived classes.

The purpose of an abstract class is to provide basic or default functionality as well as common functionality that multiple derived classes can share and modify.

Just like C# or Java, in TypeScript abstract keyword is used to define abstract classes as well as abstract methods within an abstract class. An abstract class cannot be instantiated directly. Unlike an interface, an abstract class may contain non-abstract members.

abstract.ts

abstract class Shapes {
 // must be implemented in derived classes
 abstract Area(): number;
}
class Square extends Shapes {
 side: number = 0;
 constructor(n: number) {
 super(); //mandatory to call parent class constructor
 this.side = n;
 }
 // implemented Area method
 Area(): number {
 return this.side * this.side;
 }
}
class Rectangle extends Shapes {
 length: number = 0;
 width: number = 0;
 constructor(length: number, width: number) {
 super(); //mandatory to call parent class constructor
 this.length = length;
 this.width = width;
 }
 // implemented Area method
 Area(): number {
 return this.length * this.width;
 }
}
let s = new Square(4);
s.Area(); //16

let r = new Rectangle(4, 3);
s.Area(); //12

The compiled JavaScript (ES5) code for the above TypeScript code is give below:

abstract.js

var __extends = (this && this.__extends) || function (d, b) {
 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
 function __() { this.constructor = d; }
 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Shapes = (function () {
 function Shapes() {
 }
 return Shapes;
}());
var Square = (function (_super) {
 __extends(Square, _super);
 function Square(n) {
 var _this = _super.call(this) || this;
 _this.side = 0;
 _this.side = n;
 return _this;
 }
 Square.prototype.Area = function () {
 return this.side * this.side;
 };
 return Square;
}(Shapes));
var Rectangle = (function (_super) {
 __extends(Rectangle, _super);
 function Rectangle(length, width) {
 var _this = _super.call(this) || this;
 _this.length = 0;
 _this.width = 0;
 _this.length = length;
 _this.width = width;
 return _this;
 }
 Rectangle.prototype.Area = function () {
 return this.length * this.width;
 };
 return Rectangle;
}(Shapes));
var s = new Square(4);
s.Area();
var r = new Rectangle(4, 3);
s.Area();
What do you think?

I hope you will enjoy the Classes in TypeScript while developing your web app. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.



+