2017-04-12 60 views
0

如果我有一個類foo如何確保擴展類必須在TypeScript中設置屬性值?

class Foo { 
    id: number 
    name: string 

    sayHi() { 
    console.log('hi') 
    } 
} 

我怎樣才能確保從富必須idname設定值擴展任何類?

class Bar extends Foo { 
    // must set these values 
    id = 1 
    name = 'bar' 
} 

是否有這個概念或模式的名稱?我不能將Foo作爲接口,因爲它必須具有繼承類可以使用的方法。

回答

2

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

相關問題