Microsoft/TypeScript

Binary expression in an `if` condition can't narrow identifier reassigned within expression of the optional chain

Open

#56,998 opened on Jan 9, 2024

View on GitHub
 (0 comments) (0 reactions) (0 assignees)TypeScript (6,726 forks)batch import
Experience EnhancementHelp WantedSuggestion

Repository metrics

Stars
 (48,455 stars)
PR merge metrics
 (Avg merge 6d 17h) (9 merged PRs in 30d)

Description

🔎 Search Terms

binary condition refinement predicate optional chain undefined

🕗 Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.4.0-dev.20240109#code/C4TwDgpgBAKu0F4oG8BQUoEsAmAuKAdgK4C2ARhAE4DcqAvraqJFAJIEBmVEBAxhOw4B7KEjQZmEAAoBDSjJIRgVfHEi0MmEmAA2mCNgCClTKAD8+YuSq0GqVNgi8dc6ByJ9gmIQSgBzJUFuPgFOIQAxIUo1CAAKSVV4AEp8IMoefkERAB8oD0cOTAIDRndPb18OAgBGeOrEyAAaKGAAJgaIJJR0KB0lLDDRf0DOYMywyOj4OqSNLA4oWKLhMwA6LV19IxNQKABCBCR8iELi7C7xDAHhde09A2NTEDm6KAgdAGdoTAXYpcGkAFgGkMqFhJMYvFWkkkmsNvdtk99oc8gQCkUDBcepowrdNg8ds8enR6PYyrwvD4oFVWnUOs02h0sRg+sBriJASMuOkQlkIdNgNVZj0fotlkI4Xcto9dgcjmiThjzt0ruy8QiZUSMK93l95ot-sIhkCQbyJlFIW0YZL8YjQMyruL1dLCS9SUA

💻 Code

type Type = {
  id: number;
};

type InferenceInfo = {
  typeParameter: Type;
  impliedArity?: number;
};

declare function getInferenceInfoForType(type: Type): InferenceInfo | undefined;

function fn1(t1: Type, t2: Type) {
  let info = getInferenceInfoForType(t1);
  if (info?.impliedArity !== undefined) {
    info.impliedArity; // ok
  } else if ((info = getInferenceInfoForType(t2))?.impliedArity !== undefined) {
    info.impliedArity; // 'info' is possibly 'undefined'.(18048)
  }
}

function fn2(t1: Type, t2: Type) {
  let info = getInferenceInfoForType(t1);
  if (info?.impliedArity !== undefined) {
    info.impliedArity; // ok
  } else if ((info = getInferenceInfoForType(t2))?.impliedArity) {
    info.impliedArity; // ok
  }
}

🙁 Actual behavior

The second branch in fn1 contains an error

🙂 Expected behavior

I'd expect this to be narrowed just fine - like the first branch and the second branch in fn2

Additional information about the issue

No response

Contributor guide