Skip to content

Type not narrowed when putting optional1 || optional2 condition in if statement and repeating it in its body #52210

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
5 tasks done
verhovsky opened this issue Jan 12, 2023 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@verhovsky
Copy link

verhovsky commented Jan 12, 2023

Suggestion

πŸ” Search Terms

type inference in repeated expression
repeated or condition
or condition

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

This code (playground link):

function required(x: number): number {
  return x;
}
function optional(a?: number, b?: number): number {
  if (a || b) {
    return required(a || b);
  }
  return 0;
}

produces this type error on the return required(a || b) line:

Argument of type 'number | undefined' is not assignable to parameter of type 'number'.

but TypeScript should be able to infer that a || b can only be a number not number | undefined because the || expression must be true in the if block.

πŸ“ƒ Motivating Example

I am checking two optional properties of an object and using them interchangeably. Currently I have to use an as expression.

πŸ’» Use Cases

See above.

@verhovsky verhovsky changed the title Type not narrowed when putting || condition in if statement and repeating it in its body Type not narrowed when putting optional1 || optional2 condition in if statement and repeating it in its body Jan 12, 2023
@RyanCavanaugh
Copy link
Member

Duplicate #35260

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 12, 2023
@verhovsky verhovsky closed this as not planned Won't fix, can't repro, duplicate, stale Jan 12, 2023
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

No branches or pull requests

2 participants