myContact = [
{
name: 'John',
lastName: 'Doe',
phone: 123456789
},
{
name: 'Mark',
lastName: 'Doe',
phone: 98765432
}
]
在点击事件上,添加一个条件来检查数组长度,如果长度> 2。
onClick() {
if(myContact.length > 2)
redirect page...
return false; // don't want the code to continue executing
}
错误:Typescript 类型布尔值不可分配给 void
我使用 some() 尝试了类似的方法,下面我的条件按要求工作
let checkValue = myContact.some(s => s.name === 'John')
if(checkValue)return false
但如果我尝试与我的联系人类似,E.G
let checkLength = myContact.filter(obj => obj.name).length
if(checkValue)return false // error: error: Typescript type boolean is not assignable to void
我该如何解决这个问题,
答案 0 :(得分:5)
void
类型表示该函数执行某些操作但不返回值。这意味着类型为 void
的函数也不能返回 boolean
。因为 TypeScript 期望它什么都不返回。
您很可能有一个声明如下的函数:
const functionName = (): void => {
...
}
除此之外,这似乎不是这里问题的核心。如果您希望您的函数“提前返回”并停止执行其其余逻辑。你可以明确地告诉它不返回这样的内容:
const functionName = (): void => {
if (someCondition) {
return;
}
// This code won't run if `someCondition` is true.
someOtherLogic()
}