Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use void and number type in functions with guard-clauses

Problem: I’m trying to write a simple function with a guard-clause in addition to returning a value with type: number, but ESLint is telling me "void is only valid as a return type or generic type variable"

P.S: I don’t know why ESLint is throwing me this, if I use void as a return type for guard-clause …

Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function addTwoNumbers(one: number, two: number): void | number {
  if (one < 0 || two < 0) return;
  return one + two;
}

const result = addTwoNumbers(-5, -5);
console.log(result);

I’ve tried specifying only number type to the function, but in this case ESLint is telling me "Type undefined is not assignable to type number"

>Solution :

Instead of void you need to put undefined. By default, an empty return statement will return undefined.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading