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:
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
"
CodePudding user response:
Instead of void
you need to put undefined
. By default, an empty return statement will return undefined
.