microsoft / microsoft/TypeScript

Object union member functions that return never are incorrectly narrowed

Open
#56,425 6 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 Search Terms

"never", "class union", "narrowing unions", "never union"

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about never
⏯ Playground Link

Playground Link

💻 Code
class Foo {
    defoo(): never {
        throw new Error("foo error")
    }
}

class Bar {
    defoo() { }
}

type Baz = Foo | Bar;

function defooer(baz: Baz) {
    baz.defoo() 
    // type = void
    // aka (never | void)

    return baz
    // type = Baz
    // should narrow to Bar
}
🙁 Actual behavior

baz doesn't get narrowed after calling .defoo(), even though it's impossible for any value after that point to be Foo. This seems to happen because the type of Baz["defoo"] is equal to Foo["defoo"] | Bar["defoo"] or () => never | void.

🙂 Expected behavior

baz should narrow to Bar after calling .defoo() because the return type of Foo.defoo is never.

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

Reproduce the behavior using the linked TypeScript Playground and the defooer example. Trace TypeScript's control-flow narrowing for calls whose union return type includes never; done means the value is narrowed from Foo | Bar to Bar after baz.defoo() without breaking related narrowing behavior.

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
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.