[英]Type 'number' is not assignable to type '0 | 1'
我正在嘗試將我的項目轉換為 Typescript,但遇到以下錯誤: Type 'number' is not assignable to type '0 | 1'
Type 'number' is not assignable to type '0 | 1'
代碼如下:
let pillarsCount = blockSides
.map((blockSide) => {
const sideVariations = blockSide.config || []
if (sideVariations.length === 1) {
return sideVariations.some((sv) => !!sv.hasPillar) ? 1 : 0
}
return 0
})
.reduce((a, b) => a + b, 0)
我很驚訝 TypeScript 會以這種方式推斷事物,但是您可以通過顯式鍵入reduce
操作來修復它:
let pillarsCount = blockSides
.map((blockSide) => {
const sideVariations = blockSide.config || []
if (sideVariations.length === 1) {
return sideVariations.some((sv) => !!sv.hasPillar) ? 1 : 0
}
return 0
})
.reduce<number>((a, b) => a + b, 0)
// −−−−−−−−^^^^^^^^
旁注:由於您在執行some
調用之前明確檢查sideVariations
length === 1
,因此不需要some
調用,只需使用您知道存在的單個對象:
let pillarsCount = blockSides
.map((blockSide) => {
const sideVariations = blockSide.config || []
if (sideVariations.length === 1) {
return sideVariations[0].hasPillar ? 1 : 0
// −−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
return 0
})
.reduce<number>((a, b) => a + b, 0)
// −−−−−−−−^^^^^^^^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.