簡體   English   中英

類型 'number' 不能分配給類型 '0 | 1'

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM