Typescript classes

Class

  • Typescript 每一個 class 裡面只能有一個 constructor
  • 預設的 Access Modifier 是 public
  • 存取 class 內部 properties 都必須用 this 關鍵字
class Student {
    fullname : string;
    constructor(public firstname: string, public lastname: string) {
        this.fullname = firstname + " " + lastname;
    }
}

let jason = new Student("Jason", "Lee");

Properties & Method

class Student {
    fullname : string;
    // properties
    get fullName(): string {
        return this.fullName;
    }
    
    set fullName(name:string) {
        this.fullName = name;
    }
    // methods
    printFullName():void {
        console.log(this.fullName);
    }
}

Parameter Properties

  • 在 constructor 的參數前面加入 public關鍵字,這樣會請求 typescript 來自動生成 property,下面的範例,firstNamelastName properties會被自動生成出來,所以可以直接使用
class Teacher {
    constructor(public firstName: string, public lastName: string){
        
    }
}
let teacher = new Teacher("angela", "wang");
console.log(teacher.firstName);

Static Properties

  • 在 property 的參數前面加入 static關鍵字,這樣會指定這個 property 是 class level的 property 而不是 instance level的,例如下面的範例,我們要讀取 description 這個 class level 的 property 我們需要 Teacher.description (Teacher 的 T是大寫)
class Teacher {
    static description: string = "a description";
    constructor(public firstName: string, public lastName: string){
        
    }
}
console.log(Teacher.description);

Extends

  • super 來呼叫 parent class 的 constructor,如果想 call parent的method,可以用 super.XXX()來呼叫
"use strict";

class Car {
    color: string;    
    constructor(newColor: string){
        this.color = newColor;   
    }    
    printColor(): void {
        console.log(this.color);
    }
}

class SuperCar extends Car{
    constructor(){
        super("white");
    }
    printCarColor(): void{
        super.printColor();
    }
}

let nsx = new SuperCar();
nsx.printCarColor() //output: white

Abstract Class

  • abstract 關鍵字來表明這個 class 為抽象物件,並加需要由繼承對象來實作的 method 前面加上 abstract 關鍵字
"use strict";

abstract class Car {
    color: string;    
    constructor(newColor: string){
        this.color = newColor;   
    }    
    abstract printColor(): void
}

class SuperCar extends Car{
    constructor(){
        super("white");
    }
    printColor(): void{
        console.log(this.color);
    }
}

let nsx = new SuperCar();
nsx.printColor() //output: white