4
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, E.G

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,

2
  • 2
    instead of return false, why not just return; Commented Jun 1, 2021 at 11:38
  • 3
    The code in question probably resides in a function that explicitly defines void as it's return type. As such you can't return anything. Though this is speculation as you only provide chunks of code without their context. Commented Jun 1, 2021 at 11:40

1 Answer 1

5

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()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.