TypeScript筆記(二)高階型別

jiayayao發表於2024-07-07

一、Class

class Person {
    constructor(name: string) {
        this.namee = name
        console.log(this.namee)
    }
    namee:string = '';
}
let person = new Person('Jane');

1.1 類方法

class Point {
  x: number = 0;
  y: number = 0;
  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
  scale(n:number):void {
    this.x *= n;
    this.y *= n;
  }
}

let p = new Point(1, 2);
p.scale(2);
console.log(p.x, p.y);

1.2 類繼承

兩種方式,一種是extends(繼承父類,僅JS);一種是implements(實現介面,TS提供)

class Animal {
  constructor(public name: string) {}

  move(meters: number) {
    console.log(`${this.name} moved ${meters}m.`);
  }
}

class Dog extends Animal {
  constructor(name: string) {
    super(name);
  }
  bark() {
    console.log("Woof! Woof!");
  }
}
interface sing {
    sing(): void;
}

class singer implements sing {
    sing() {
        console.log("hello world");
    }
}

類可見性:public/protected/private

protected:僅所在類和子類(不含例項物件)中可見

private:僅所在類可見

1.3 只讀修飾符

readonly: 只讀,防止在建構函式之外,對屬性進行賦值;只能修飾屬性,不能修飾方法;

class Person {
    readonly name:string;
    constructor(name:string){
        this.name = name;
    }
}

let p = new Person('Tom');
p.name = 'Jerry'; // 報錯

1.4 型別相容性

兩種:1、Structural Type System(結構化型別系統)2、Nominal Type System(標明型別系統)

TS採用的是結構化型別系統,關注的是值所具有的形狀。

少的引數賦值給多的引數是沒有問題的,反之報錯。

type F1 = (a:number) => void
type F2 = (a:number, b:number) => void

let f1:F1 = (a) => {
    console.log(a)
}
let f2:F2 = f1

P47

相關文章