2016-12-06 90 views
3

我有這樣的代碼:如何獲得TypeScript來確定我的函數不可能返回?

function A(): never { 
    throw new Error("fail"); 
} 

function B(): never { 
    A(); 
} 

而且我得到這個錯誤:

index.ts(5,36): error TS2534: A function returning 'never' cannot have a reachable end point. 

爲什麼會出現這個錯誤?顯然,A從不返回,因此B沒有可達的終點。

回答

4

這是編譯器的限制。瑞安卡瓦諾解釋here

The limitation here has to do with the way the compiler is designed -- control flow analysis happens before typechecking, but we would need type information (as well as identifier resolution) to determine that the fail() call points to a function that is : never

fail()呼叫這句話的背景下的確基本上是同樣的事情A()在這裏提出的問題。我從上面的報價推斷,到控制流分析完成時,A()無法返回的事實還不得而知,因此假定在B末尾隱含return undefined;將被執行,因此B將會執行返回undefined而不是根本不返回。修正如在發表評論的問題報告中提到的,只需在呼叫之前添加一個return,然後再調用永不返回的函數:

function B(): never { 
    return A(); 
}