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 类型 bool 值不可分配给 void我尝试使用 some() 进行类似的操作,以下我的条件按要求工作
let checkValue = myContact.some(s => s.name === 'John')
if(checkValue)return false
但如果我尝试与我的联系人类似,E.Glet checkLength = myContact.filter(obj => obj.name).length
if(checkValue)return false // error: error: Typescript type boolean is not assignable to void
我该如何解决这个问题,
最佳答案
一个 void
type 表示函数做了一些事情但不返回值。这意味着类型为 void
的函数无法返回 boolean
任何一个。正如 TypeScript 所期望的那样,它什么也不返回。
您很可能有一个函数声明如下:
const functionName = (): void => {
...
}
除此之外,这似乎不是这里问题的核心。如果您希望您的函数“提前返回”并停止执行其其余逻辑。你可以明确地告诉它不返回这样的东西:
const functionName = (): void => {
if (someCondition) {
return;
}
// This code won't run if `someCondition` is true.
someOtherLogic()
}
关于javascript - typescript 类型 boolean 不能分配给 void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67788111/