babelcodes
9/16/2017 - 6:59 PM

TypeScript > Class

TypeScript > Class ▶︎ http://babel.codes/TypeScript/Class

/**
 * Table of content:
 *
 * 1/ Class
 * 2/ Constructor
 * 3/ Properties
 * 4/ Method
 * 5/ Visibility: private - protected - public/default
 * 6/ Readonly
 * 7/ Inheritance
 * 8/ Abstract
 * 9/ Accessors: getters / setters
 * 10/ static
 *
 */

class Person {                                             // 1/ Class

    year: number;                                          // 3/ Properties
                                                           // 5/ Visibility - public/default

    protected name: string;                                // 5/ Visibility - protected

    constructor(name: string) {                            // 2/ Constructor
        this.name = name;
    }

    static numberOfLegs: number = 2;                       // 10/ static

    public getNumberOfLegs(): number {                     // 4/ Method
        return Person.numberOfLegs;
    }
}

class Employee extends Person {                            // 7/ Inheritance
    private department: string;                            // 5/ Visibility - private

    constructor(name: string, department: string) {
        super(name);
        this.department = department;
    }

    public getElevatorPitch() {
        return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }

    private _fullName: string;                             // 9/ Accessors - getters / setters
    get fullName(): string {
        return this._fullName;
    }
    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        } else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // error



class Octopus {                                            // 6/ Readonly
    readonly name: string;
    readonly numberOfLegs: number = 8;

    constructor(theName: string) {
        this.name = theName;
    }
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // error! name is readonly.



abstract class Animal {                                    // 8/ Abstract
    abstract makeSound(): void;

    move(): void {
        console.log("roaming the earth...");
    }
}
class Cat extends Animal {
    makeSound(): void {
    }
}