Author : MD TAREQ HASSAN

Introduction

Traditional JavaScript uses functions and prototype-based inheritance, where TypeScript uses object-oriented class-based approach.

Note:
Starting with ECMAScript 2015, also known as ECMAScript 6, JavaScript programmers are able to build their applications using this object-oriented class-based approach

Details: https://www.typescriptlang.org/docs/handbook/classes.html

Example

class Greeter {

    greeting: string;
	
    constructor(message: string) {
        this.greeting = message;
    }
	
    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");

Inheritance

class Bar extends Foo {

    constructor(name: string) { super(name); }
	
    hover(distanceInMeters = 5) {
        // ... ... ...
    }
}

Access modifiers

Getter Setter

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (newName && newName.length > fullNameMaxLength) {
            throw new Error("fullName has a max length of " + fullNameMaxLength);
        }
        
        this._fullName = newName;
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

Static property

class Foo {

    static message: string = "Hovermind";
	
    // ... ... ...
}

let msg = Foo.message;