I recently encountered an issue where TypeScript incorrectly identifies a variable as possibly being undefined
. Here is a simplified example:
const func = (val1?: boolean, val2?: boolean) => {
if (!val1 && !val2) return;
let result: boolean;
if (val1) result = false;
else result = val2;
}
In the line else result = val2;
, val1
is either false
or undefined
, and val2
must be true
because otherwise !val1 && !val2
would have been true. Despite this, TypeScript throws an error stating:
Type 'boolean | undefined' is not assignable to type 'boolean'.
To temporarily resolve the issue, I added || !val2
to the line if (val1) result = false;
:
const func = (val1?: boolean, val2?: boolean) => {
if (!val1 && !val2) return;
let result: boolean;
if (val1 || !val2) result = false;
else result = val2;
}
I am intrigued by why this error occurs and why TypeScript cannot recognize that the variable cannot be undefined
.