microsoft / microsoft/TypeScript

JS ES6 class derived member functions typed with literals don't get assigned the correct type

Open
#44,640 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

In rare cases (such as when literals are used in a type constraint), ES6 class overridden functions will cause strange issues when returning said literals from the derived function.

🔎 Search Terms

ts es6 class derived

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

Playground link with relevant code

💻 Code
class Base
{
    test()
    {
        if (Math.random() > 0.5)
            return 5;

        return false;
    }
}

class Derived extends Base
{
    // error here: for some reason, Derived::test() is typed as "() => boolean"
    // even though the literal false is being returned, and as such it says it can't
    // match Base::test
    test()
    {
        return false;
    }
}

🙁 Actual behavior

The derived function's auto-typing assumes it is the literals' actual type, such as number or boolean, instead of the literals themselves. Derived::test, if not overridden, is typed as () => false, which should match () => 5 | false, but because it's typed as boolean instead it breaks (this only seems to happen if we're overriding a base member function)

🙂 Expected behavior

The derived function should be able to match if the typing is handled as normal.

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 linked TypeScript Playground reproduction and compare the inferred types for Base::test and Derived::test. Trace how overridden ES6 methods infer literal return types, then verify that the derived function is accepted against the base literal union without losing the literal types.

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
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.