microsoft / microsoft/TypeScript

Allow subclasses to declare overloads of methods

Open
#54,747 1 comment 0 reactions 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

Suggestion

Allow subclasses to declare an overload of a superclass method:

This would be useful with addEventListener() in order to provide the correct event type for an event name:

class MyElement extends HTMLElement {
  declare addEventListener(type: 'my-event', listener: (this: MyElement, ev: MyEvent) => any, options?: boolean | AddEventListenerOptions): void;
}

🔍 Search Terms

Various combinations: addEventListener subclass declare overload method

A lot of issues were returned from queries, I could have missed something.

✅ 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

See above. I'm not sure the reason for not allowing declare on methods currently, so hopefully that could be relaxed.

📃 Motivating Example

See above.

Right now you would have to augment the HTMLElementEventNameMap, but that makes events global, which they might not be if they don't bubble.

💻 Use Cases

See above.

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 by investigating TypeScript's handling of declare methods and inherited method overloads. Compare the proposed subclass addEventListener declaration with the current behavior and determine the type-checking rules required. Done should allow the subclass overload without changing emitted JavaScript while preserving compatibility with the superclass method.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.