Skip to content

Compiler fails to infer that a Date variable is not null even though it's obvious #41266

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
devuxer opened this issue Oct 27, 2020 · 1 comment · Fixed by #44730
Closed

Compiler fails to infer that a Date variable is not null even though it's obvious #41266

devuxer opened this issue Oct 27, 2020 · 1 comment · Fixed by #44730
Labels
Duplicate An existing issue was already created

Comments

@devuxer
Copy link

devuxer commented Oct 27, 2020

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.

Playground Link: https://www.typescriptlang.org/play?#code/MYewdgzgLgBAJgQygUxgXhgc2VAIk5ACgEoBuAKHIDMBXMYKAS3Cx3xRJgG9yY+YATjhoCwMdsgB0YEAHdOAPhgBGAAzqYAfhhhks8QU4AuHTQA2ZigF9KoSLACe6GAEJEKGAB9P8ApIBuCGY0yADyVIoq6qoU5IxUMIQOxNy8-HYQIGZSZiCYhABETowQMFACNFAAFg4FZORWMMhmEKg8-DAZWTl5hNhQALLg1YTuyMT1NtR0DMxi-UNgI4HByCYSKe38QlAiYishkgvDVSTWQA

Related Issues: (not able to find any -- not sure what other key words to search for)

@MartinJohns
Copy link
Contributor

Duplicate of #12184.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants