給Foo
要求他們作爲參數的構造函數:
class Foo {
constructor(public id: number, public name: string) {
// Validate them here if desired
}
sayHi() {
console.log('hi');
}
}
由於子類必須調用它的父類的構造函數(或明或暗地),企圖沒有必要的參數傳遞將得到標記這樣做打字稿編譯:Supplied parameters do not match any signature of call target.
例如,這些都失敗:
class Bar extends Foo {
}
const b = new Bar(); // Supplied parameters do not match any signature of call target.
和
class Bar extends Foo {
constructor() {
super(); // Supplied parameters do not match any signature of call target.
}
}
注有趣的打字稿功能使用的有:因爲我們給的構造函數的參數的訪問修飾符,實例屬性會自動創建並設置這些值時,調用構造函數。這相當於:
class Foo {
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
// Validate them here if desired
}
sayHi() {
console.log('hi');
}
}
(因爲默認修飾符是public
)