TypeScript Abstraction Example

Abstraction means hiding lower-level details and exposing only the essential and relevant details to the users.
The concept behind abstraction is that we are hiding the complexity of the implementation from inherited classes and we allow them to implement the functionality themselves.
In TypeScript, abstraction can be achieved by using the abstract keyword - which can be applied to both classes and methods specified in classes.

TypeScript Abstraction Example

Let's go ahead and create an abstract class with an abstract method as well:
abstract class Employee {

    name: string;
    paymentPerHour: number;

    constructor(name: string, paymentPerHour: number) {
        this.name = name;
        this.paymentPerHour = paymentPerHour;
    }

    public abstract calculateSalary(): number;
}
If we now attempt to instantiate this class we'll get an error:
In order to implement our abstract class we need to create a subclass and extend it using the extends keyword - and we also need to make sure that we implement the method calculateSalary() in our subclass, otherwise, we'll receive an error as shown in the above diagram.
Let's create a Contractor and FullTimeEmployee subclasses which extends Employee abstract class and implement the abstract method calculateSalary().
Here is complete code to demonstrate Abstraction in TypeScript:
abstract class Employee {

    name: string;
    paymentPerHour: number;

    constructor(name: string, paymentPerHour: number) {
        this.name = name;
        this.paymentPerHour = paymentPerHour;
    }

    public abstract calculateSalary(): number;
}

class Contractor extends Employee {

    workingHours: number;
    constructor(name: string, paymentPerHour: number, workingHours: number) {
        super(name, paymentPerHour);
        this.workingHours = workingHours;
    }

    calculateSalary(): number {
        return this.paymentPerHour * this.workingHours;
    }
}

class FullTimeEmployee extends Employee {
    constructor(name: string, paymentPerHour: number) {
        super(name, paymentPerHour);
    }

    calculateSalary(): number {
        return this.paymentPerHour * 8;
    }
}


let contractor: Employee;
let fullTimeEmployee: Employee;
contractor = new Contractor('Ramesh contractor', 10, 5);
fullTimeEmployee = new FullTimeEmployee('Ramesh full time employee', 8);

console.log(contractor.calculateSalary());
console.log(fullTimeEmployee.calculateSalary());
Output:
50
64

How to run the above code and see the output?

Follow the below steps to run typeScript programs:
  1. Create a TypeScript file named "abstract-class.ts" and add the above code example to it.
  2. Make sure that you have installed Node.js in your machine. If not, follow this link https://nodejs.org/en/
  3. Make sure that you have installed TypeScript package. If you haven't installed it then install the TypeScript Package using the Node Package Manager (NPM). To begin with the installation, open any Console Window ( cmd.exe) and enter the following command in the prompt:
npm install -g typescript
  1. Let's run above typescript file using the following command:
c:\user\typescript-tutorial> tsc .\abstract-class.ts
On compiling, it will generate the following JavaScript code.
var __extends = (this && this.__extends) || (function() {
    var extendStatics = function(d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({
                    __proto__: []
                }
                instanceof Array && function(d, b) {
                    d.__proto__ = b;
                }) ||
            function(d, b) {
                for (var p in b)
                    if (b.hasOwnProperty(p)) d[p] = b[p];
            };
        return extendStatics(d, b);
    };
    return function(d, b) {
        extendStatics(d, b);

        function __() {
            this.constructor = d;
        }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Employee = /** @class */ (function() {
    function Employee(name, paymentPerHour) {
        this.name = name;
        this.paymentPerHour = paymentPerHour;
    }
    return Employee;
}());
var Contractor = /** @class */ (function(_super) {
    __extends(Contractor, _super);

    function Contractor(name, paymentPerHour, workingHours) {
        var _this = _super.call(this, name, paymentPerHour) || this;
        _this.workingHours = workingHours;
        return _this;
    }
    Contractor.prototype.calculateSalary = function() {
        return this.paymentPerHour * this.workingHours;
    };
    return Contractor;
}(Employee));
var FullTimeEmployee = /** @class */ (function(_super) {
    __extends(FullTimeEmployee, _super);

    function FullTimeEmployee(name, paymentPerHour) {
        return _super.call(this, name, paymentPerHour) || this;
    }
    FullTimeEmployee.prototype.calculateSalary = function() {
        return this.paymentPerHour * 8;
    };
    return FullTimeEmployee;
}(Employee));
var contractor;
var fullTimeEmployee;
contractor = new Contractor('Ramesh contractor', 10, 5);
fullTimeEmployee = new FullTimeEmployee('Ramesh full time employee', 8);
console.log(contractor.calculateSalary());
console.log(fullTimeEmployee.calculateSalary());
Let's run above JavaScript file using the following command:
c:\user\typescript-tutorial> node .\abstract-class.ts
Output:
50
64
Learn more about TypeScript at TypeScript Tutorial with Examples.

Comments