首页 > 解决方案 > Type 'number' is not assignable to type '0 | 1'

问题描述

I'm trying to convert my project to Typescript, but I ran into the following error: Type 'number' is not assignable to type '0 | 1' The code looks as follows:

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)

标签: javascriptreactjstypescript

解决方案


I'm surprised that TypeScript is inferring things that way, but you can fix it by explicitly typing the reduce operation:

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)
// −−−−−−−−^^^^^^^^

Playground link


Side note: Since you're explicitly checking that sideVariations has length === 1 before doing the some call, there's no need for the some call, just use the single object you know is there:

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)
// −−−−−−−−^^^^^^^^

Playground link


推荐阅读