2013-03-11 86 views
2

我爲我的服務結果創建了一個TypeScript接口。現在我想爲裏面的兩個函數定義一個基本的功能。問題是,我得到一個錯誤:在TypeScript中實現接口的原型

The property 'ServiceResult' does not exist on value of type 'Support'.

我用WebStorm發展(VS2012讓我很緊張,因爲對大項目凍結 - 等待更好的整合:P)。

這裏是我如何做到這一點:

module Support { 
    export interface ServiceResult extends Object { 
     Error?: ServiceError; 
     Check?(): void; 
     GetErrorMessage?(): string; 
    } 
} 

Support.ServiceResult.prototype.Check =() => { 
    // (...) 
}; 

Support.ServiceResult.prototype.GetErrorMessage =() => { 
    // (...) 
}; 

我也試圖在我的原型移動到模塊,但同樣的錯誤還是......(當然我刪除Support.前綴)。

回答

4

它看起來像你試圖添加實現到接口 - 這是不可能的。

你只能添加到一個真正的實現,例如一個類。您也可以決定將實現添加到類定義中,而不是直接使用prototype

module Support { 
    export interface ServiceResult extends Object { 
     Error?: ServiceError; 
     Check?(): void; 
     GetErrorMessage?(): string; 
    } 

    export class ImplementationHere implements ServiceResult { 
     Check() { 

     } 

     GetErrorMessage() { 
      return ''; 
     } 
    } 
} 

Support.ImplementationHere.prototype.Check =() => { 
    // (...) 
}; 

Support.ImplementationHere.prototype.GetErrorMessage =() => { 
    // (...) 
}; 
2

由於編譯的JavaScript根本不會發出與接口相關的任何內容,因此無法對接口進行原型設計。該接口純粹用於編譯時使用。看看這個:

這打字稿:

interface IFoo { 
    getName(); 
} 

class Foo implements IFoo { 
    getName() { 
     alert('foo!'); 
    } 
} 

編譯成這個JavaScript:

var Foo = (function() { 
    function Foo() { } 
    Foo.prototype.getName = function() { 
     alert('foo!'); 
    }; 
    return Foo; 
})(); 

有一個在結果沒有IFoo,在所有 - 這就是爲什麼您獲得的錯誤。通常,您不會爲接口創建原型,您可以爲實現接口的類創建原型。

您甚至不必親自編寫原型,只需實現接口就足夠了,TypeScript編譯器將爲您添加原型。