javascript - 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)
解决方案
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)
// −−−−−−−−^^^^^^^^
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)
// −−−−−−−−^^^^^^^^
推荐阅读
- c# - App.Config GetSection 不返回小节值
- javascript - document.getElementsByTagName 在 iframe 中不起作用?
- bash - 按下的 bash 行为
两次用于文件名完成 - postgresql - 从 Heroku 到 Digital Ocean 的数据库传输
- python - sum() 得到了一个意外的关键字参数 'where'
- python - 从数据框中删除行,其中从第三列开始的每个值都是 0
- python-3.8 - python中的简单BMI计算器,但while循环不会因输入错误而执行
- sql-server - 如何将来自游标的多个结果组合或存储到Sql Server中的一个结果集中?
- python - 如何编写一个接受字典并按字母顺序打印字典条目的函数?
- python - 无法定位元素,无法抓取“评论”