microsoft / microsoft/TypeScript

Inverted union type narrowing was broken in 4.9

Open
#58,861 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Control Flow Help Wanted
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 Search Terms

"union type", "narrowing", "inverted", "4.9"

🕗 Version & Regression Information
⏯ Playground Link

Playground link

💻 Code
interface Foo { foo: string; }

interface Bar { bar: string; }

interface Baz { baz: string; }

function myFunction(input: Foo | Bar | Baz) {
    const isBaz = 'baz' in input;
    const isBar = 
      //'bar' in input; // This works to narrow `bar` when true and narrow `foo` in the else block
      !('foo' in input) && !isBaz; // This works to narrow `bar` when true but does not narrow `foo` in the else block
    let x: string;
    if (isBaz) {
      x = input.baz;
    } else if (isBar) {
      x = input.bar;
    } else {
      // In 4.8.4 and earlier, `input` is narrowed to `Foo`
      // In 4.9.5 and later, `input` is narrowed to `Foo | ((Foo | Bar) & Record<"baz", unknown>)`
      x = input.foo;
    }
}
🙁 Actual behavior

In 4.9.5 and later, in the else block, input.foo incorrectly narrows and errors

🙂 Expected behavior

In 4.8.4 and earlier, in the else block, input.foo correctly narrows

Additional information about the issue

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the supplied Playground link and reproduce the difference between TypeScript 4.8.4 and 4.9.5 using the example in the issue. Trace the type narrowing for the inverted union checks in the type checker. Done means the else branch narrows input to Foo and accepts input.foo without an error in the affected versions.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.