【问题标题】:Typescript type boolean is not assignable to void打字稿类型 boolean 不可分配给 void
【发布时间】:2021-08-19 14:36:14
【问题描述】:
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 类型 boolean 不能分配给 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

我该如何解决这个问题,

【问题讨论】:

  • 而不是返回false,为什么不只是return;
  • 有问题的代码可能驻留在一个函数中,该函数将void 明确定义为其返回类型。因此,您不能返回任何东西。虽然这是推测,因为您只提供没有上下文的代码块。

标签: javascript typescript


【解决方案1】:

void 类型意味着该函数做了一些事情但不返回值。这意味着void 类型的函数也不能返回boolean。正如 TypeScript 所期望的那样,它什么也不返回。

你很可能有一个这样声明的函数:

const functionName = (): void => {
  ...
}

除此之外,这似乎不是这里问题的核心。如果您希望您的函数“提前返回”并停止执行其余的逻辑。你可以明确地告诉它不返回这样的东西:

const functionName = (): void => {
  if (someCondition) {
    return;
  }

  // This code won't run if `someCondition` is true.
  someOtherLogic()
}

【讨论】:

    猜你喜欢
    • 2018-01-04
    • 2018-09-29
    • 1970-01-01
    • 2016-06-24
    • 2020-08-27
    • 2021-10-11
    • 2016-12-17
    • 2020-06-29
    • 2017-06-29
    相关资源
    最近更新 更多