microsoft / microsoft/TypeScript

Polymorphic `this` and Generics

Open
#6,223 20 comments 30 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Needs Proposal Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

First, thank you team for polymorphic this. It is really handy!

I think I ran into a case though that I am finding challenging, when I need to return a this, but the generics might have changed. For example:

class A<T> {
    private items: T[] = [];
    map<U>(callback: (item: T, idx: number, a: this) => U): this {
        // boring implementation details
    });
}

Where I want to be able to change the generic type for the class with a function, but I will be contracting to return the "current" class, but I want to guard different generics. The following seems logical to me, but doesn't appear to be currently supported:

class A<T> {
    private items: T[] = [];
    map<U>(callback: (item: T, idx: number, a: this) => U): this<U> {
        // boring implementation details
    });
}

Where if no generics arguments are supplied, it is inferred to be the current ones, where as if they are supplied they are substituted.

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

The issue describes a proposed interaction between polymorphic this and generic type substitution, but names no implementation files, tests, or entry points. Begin by locating the compiler's handling of polymorphic this and generic instantiation; done would mean the requested this<U> behavior is supported with the stated inference and substitution rules, covered by tests.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.