Here is the code snippet in question:
function test(a: number | undefined, b: number | undefined) {
if (!a && !b) {
console.log('Neither are present');
return;
}
if (!b && !!a) {
console.log('b is not present, we only found a - do a thing with a');
return;
}
if (!a && !!b) {
console.log('a is not present, we only found b - do a thing with b');
return;
}
// At this point, I'd like the compiler to know that both a and b are not undefined,
// but it doesn't.
console.log(a + b);
}
The issue arises at the end where the compiler gives errors 'a' is possibly 'undefined'
and 'b' is possibly 'undefined'
.
In reality, the code cannot reach that final line without both a
and b
being defined.
The conditionals are more complex due to the requirement of utilizing one parameter if the other is absent.
Any insights on what might be overlooked here, or perhaps there exists a more idiomatic TypeScript approach to tackle this logic?
Appreciate the help!