简体   繁体   中英

Typescript type boolean is not assignable to void

myContact = [
 {
  name: 'John',
  lastName: 'Doe',
  phone: 123456789
 },
 {
  name: 'Mark',
  lastName: 'Doe',
  phone: 98765432
 }
]

On click event, add a condition to check the array length, if the length > 2.

onClick() {

 if(myContact.length > 2)
     redirect page...
    return false; // don't want the code to continue executing
 }

error: Typescript type boolean is not assignable to void

I try something similar using some(), the below my conditions works as required

let checkValue = myContact.some(s => s.name === 'John')
if(checkValue)return false

But if I try similar with my contact, EG

let checkLength = myContact.filter(obj => obj.name).length
if(checkValue)return false   // error: error: Typescript type boolean is not assignable to void

How can I fix this issue,

A void type means that the function does something but doesn't return a value. That means that a function with the type void can't return a boolean either. As TypeScript expects it to return nothing.

You most likely have a function declared something like this:

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

Besides that, this doesn't seem to be the core of the issue here. If you want your function to "return early" and stop executing the rest of its logic. You can explicitly tell it to return nothing like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM