可以說我有一些像這樣的簡單邏輯:
let bool = false
const seven = 7
const arr = [1,2,3,4,5,6,7]
arr.forEach(element => {
if (element === seven) {
bool = true
}
});
現在,如果“bool”已設定為 true,我將不呼叫函式:
if (bool === true){
doSomething()
}
在這種情況下,打字稿會出錯:
This condition will always return 'false' since the types 'false' and 'true' have no overlap.
即使在邏輯上我知道 bool 將在條件塊被觸發時為真,打字稿也會抱怨。我該如何解決這個問題?
uj5u.com熱心網友回復:
我不知道 Typescript 編譯器會抱怨這樣的事情,但再次使用這樣的條件陳述句是一種奇怪的方式,因為:
if (bool === true)
是相同的:
if (bool)
但是,是的,您可以:
- 用正常的方式寫條件:(
if (bool) { ... }強烈推薦) - 強制型別為布爾型:(
if((bool as boolean) === true ) { ... }它有效,但請不要這樣做)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481456.html
