Skip to content

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

Closed as not planned
@verhovsky

Description

@verhovsky

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions