Financial Year 2023 End Sale: Get upto 40% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
Class in TypeScript

Class in TypeScript

22 Dec 2023
Advanced
6.12K Views
12 min read
Learn via Video Course & by Doing Hands-on Labs

TypeScript Programming Course

ECMAScript 6 or ES6 provides a class type to build the JavaScript applications by using an object-oriented class-based approach. TypeScript extends ES6 class type with typed members and access modifiers like classes in C# or Java programming languages, and declaring & using classes is straightforward just like we use classes in JavaScript.

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 class has been created using the keyword "class" of the student that contains properties such as rollNo and name, it has one internal function called "showDetails()" that can be accessed by creating the object of the student class.

The compiled JavaScript (ES5) code for the above TypeScript code is given 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 a typescript constructor, you can make public, private, or protected instance members of a class and the constructor may have a set of variables that can be assigned with the default values.

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 given 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 the constructor function type. Within static functions and static accessors, this represents the constructor function type.

Static members are accessible by using the class name only, not by using the class instance. Inside the 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 given 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);

We have seen examples that how the static member can be created and used, but you may have certain questions that can we create a class as a "Static" member, this is not possible because the static keyword is created for providing the memory and executing its logic without creating the Objects, a class does not have a value logic directly as such.

Access Modifiers

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

  1. Public - By default, members (properties and methods) of the 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 type 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 given 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 read-only modifiers on the property level by using the readonly keyword. The Readonly properties must be initialized at their declaration or in the constructor.

By using readonly modifiers, we can not re-assign any values outside the constructor of the class, if we still do that, the error will be thrown as "XYZ is a read-only property".

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 given 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 gives us control over how a member of an object is accessed and set.

TypeScript supports two types of accessors such as to get() and set() and if we have to get() accessor defined but no set() then the value will act as a read-only property eventually.

Note: With the release of TypeScript 4.3 and above, we can have different types with getting and set accessors.

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 given 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 the child class, you can override or modify the behaviors of its parent class and also can add a 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 a 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 given 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 that 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 given 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?

TypeScript is an extended version of the JavaScript scripting language that uses JavaScript’s runtime environment with a compile-time strict type checking. These features and developer-friendly nature allows developers to use the JavaScript ecosystem and language features at the fullest, while also adding optional static type-checking, enum data types, classes, interfaces, and many more.

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.

Take our free typescript skill challenge to evaluate your skill

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET CHALLENGE

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this