Closed
Description
TypeScript Version: 4.03
Search Terms: Date, truthy, inference
Code
const date = getDate();
function getDate() {
return Date.now() > 1000 ? new Date() : null;
}
const y = !date || date.valueOf() > 1000;
if (y) {
console.log("y is truthy");
} else {
console.log(getMonth(date));
}
function getMonth(value: Date) {
return value.getMonth();
}
Expected behavior:
No error trying to pass date
to getMonth
, since it has been proved to be a non-null date due to variable y
being false.
Actual behavior:
The following error is displayed for date
:
Argument of type 'Date | null' is not assignable to parameter of type 'Date'. Type 'null' is not assignable to type 'Date'.
Note that if you do if (!date || date.valueOf() > 1000
instead of if (y)
, the error disappears, so that one small bit of indirection seems to throw off the compiler.
Related Issues: (not able to find any -- not sure what other key words to search for)