2017-04-19 40 views
5

我從打字稿得到這個奇怪的錯誤被稱爲:TS - 只有一個void函數可以用「新」關鍵字

"Only a void function can be called with the 'new' keyword."

什麼?

enter image description here

的構造函數,只是看起來像:

function Suman(obj: ISumanInputs): void { 

    const projectRoot = _suman.projectRoot; 

    // via options 
    this.fileName = obj.fileName; 
    this.slicedFileName = obj.fileName.slice(projectRoot.length); 
    this.networkLog = obj.networkLog; 
    this.outputPath = obj.outputPath; 
    this.timestamp = obj.timestamp; 
    this.sumanId = ++sumanId; 

    // initialize 
    this.allDescribeBlocks = []; 
    this.describeOnlyIsTriggered = false; 
    this.deps = null; 
    this.numHooksSkipped = 0; 
    this.numHooksStubbed = 0; 
    this.numBlocksSkipped = 0; 

} 

我不知道是什麼問題。我嘗試添加和刪除返回類型(void),但是什麼也沒做。

+0

'new(function Class(){})()'引發警告。 – Cody

回答

3

的問題是,ISumanInputs不包括你,包括你的電話你沒有正確履行IsumanInputs接口的屬性的一個或多個。

在額外的屬性情況下,你應該得到一個「額外」的錯誤:

Object literal may only specify known properties, and 'anExtraProp' does not exist in type 'ISumanInputs'

在丟失的財產的情況下,你會得到一個不同的「額外」的錯誤:

Property 'timestamp' is missing in type '{ fileName: string; networkLog: string; outputPath: string; }'.

有趣的是,如果將參數的定義移出多餘的屬性則不再失敗:

const data = { 
    fileName: "abc", 
    networkLog: "", 
    outputPath: "", 
    timestamp: "", 
    anExtraProperty: true 
}; 

new Suman(data); 
+0

謝謝!讓我試試看 –

3

正如肖恩指出的那樣,這是一個不太明顯的論點類型不匹配的結果。

如果您有更深的理由感興趣:當函數的參數未檢查時,tsc推斷返回類型爲特殊類型never(覆蓋您指定的void)。具有這種功能的new將導致TS2350 Only a void function can...

這段代碼可以觸發TS2350而不會有錯誤的參數。

function Ctor(): never { 
    throw "never return"; 
} 

const v = new Ctor(); 
相關問題