Skip to content
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

Type inference bails when encountering any in conditional expression #52689

Closed
mhofman opened this issue Feb 8, 2023 · 2 comments
Closed

Type inference bails when encountering any in conditional expression #52689

mhofman opened this issue Feb 8, 2023 · 2 comments
Labels
Not a Defect This behavior is one of several equally-correct options

Comments

@mhofman
Copy link

mhofman commented Feb 8, 2023

Bug Report

πŸ”Ž Search Terms

type inference any conditional expression

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

declare function getMaybeNumber(): any;
// declare function getMaybeNumber(): number | undefined;

function checkNum(num?: number) {
    if (!num) {
      num = getMaybeNumber() || 42;
    //   if (!num) num = 42
    }
    if (num < 50){
        throw new Error()
    };
}

πŸ™ Actual behavior

'num' is possibly 'undefined'.

πŸ™‚ Expected behavior

type of num narrowed to number or widened to any

More information

The narrowing work correctly if the return type is not any.

The narrowing also works if using an if statement instead of a conditional expressions. Likely related to the design limitation that was mentioned in #50739. However given that type narrowing works if the return type is not any there is obviously some type inference possible in conditional expressions.

@RyanCavanaugh RyanCavanaugh added the Not a Defect This behavior is one of several equally-correct options label Feb 14, 2023
@RyanCavanaugh
Copy link
Member

The current behavior is the most-conservative since there's really no telling what is happening on that line of code, while still not completely wrecking type safety on num throughout the body of the function. I don't think a change in either direction as proposed is a net improvement.

@github-actions
Copy link

github-actions bot commented Jun 8, 2023

This issue has been marked as 'Not a Defect' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Jun 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Not a Defect This behavior is one of several equally-correct options
Projects
None yet
Development

No branches or pull requests

2 participants