2016-05-24 57 views
1

這是一個簡單的例子。不正確的類型沒有檢測到typecript編譯器?

我使用這種設計的MVC架構:你可以爲一個視圖模型和V(和派生類)認爲M(和派生類)的:

abstract class M { abstract update() : void; } 
abstract class V { abstract updateView (m: M) : void; } 

class M1 implements M { 
    fV: V; 
    fName: string; 
    constructor() { this.fV = new V1(); this.fName="M1"; } 
    getName() : string { return this.fName; } 
    update() : void { this.fV.updateView (this); } 
} 

class M2 implements M { 
    fV: V; 
    constructor() { this.fV = new V1(); } 
    update() : void { this.fV.updateView (this); } 
} 

// ==> V1 implementation of V is incorrect but not detected by the compiler 
class V1 implements V { 
    updateView (m: M1) : void { console.log (m.getName() + ": update called"); } 
} 

var m1 = new M1(); 
m1.update(); 

// ==> incorrect use of V1 by M2 not detected at compile time, generates an error at run time 
var m2 = new M2(); 
m2.update(); 

注意下面在編譯時產生一個錯誤:

abstract class X { abstract amethod() : void; } 
class V2 implements V { 
    updateView (m: X) : void { console.log ("V2 update called"); } 
} 

第一個代碼有問題或者是編譯器有問題嗎?

在此先感謝您的幫助

大教堂

回答

0

這編譯爲我(TS 1.8.10)

abstract class M { abstract update() : void; } 
abstract class V { abstract updateView (m: M) : void; } 

abstract class X extends M { abstract amethod() : void; } 
class V2 implements V { 
    updateView (m: X) : void { console.log ("V2 update called"); } 
} 

的變化是,X必須擴展M(因爲V預計的M在updateView

+0

當然,我知道。問題不在於第二部分(我不想那樣編譯),而是用第一個例子:我不想讓它編譯太多(但它確實)。 –