microsoft / microsoft/TypeScript

Type narrowing of `super` when using `this`

Open
#55,155 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: This-Typing
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

🔎 Search Terms

super, this, class

🕗 Version & Regression Information

Nightly

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.2.0-dev.20230720#code/MYGwhgzhAECCB2BLAtmEAeAKgPmgbwChpjoBTMAFy2wAoKALRCALjiVQxwEp8iT+GAJwD2Ad2jxS4gKKCRgmgHJMjGABNhpCPArRUFCqUGKuAbj7EAvgWsFQkGABFhAc2pkAHofhqYCFGjuhPzkVACqtAxMrM5uETzB-CQQAK4ADkYAdKE0ZtAA9PnQKqTQFACeGdBMbAGc2NmU1HSqrP4c1FysAG7CiGoWSUPDhcX0pRVVEPTCKSBq0ABGpe2BEY3hka21HfE9fQP81tZAA

💻 Code
class Animal<T> {
    eat<T>(this: Animal<T>) {
        throw new Error('This doesnt matter');
    }
}

class Dog<T> extends Animal<T> {
    eat<U>(this: Dog<U>) {
        super.eat(); // The type is Animal<T>.eat<T>(this: Animal<T>): void
                     // The type should be Animal<U>.eat<U>(this: Animal<U>): void
    }
}
🙁 Actual behavior

super.eat() is typed as Animal<T>.eat<T>(this: Animal<T>): void

🙂 Expected behavior

super.eat() should be typed as Animal<U>.eat<U>(this: Animal<U>): void since this is declared as Dog<U> which is a subclass of Animal<U>.

One can workaround this by writing super.eat<U>(), but the signature then becomes goofy (it becomes Animal<T>.eat<U>(this: Animal<U>): void)

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 and reproduce the difference between the current and expected types for super.eat() in the generic Animal and Dog classes. Trace the compiler's handling of this types in super property access, then add a regression test and confirm that super.eat() preserves the U-specific type without requiring an explicit type argument.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.