microsoft / microsoft/TypeScript
Generic methods with type parameters in generic constraints cannot be overridden
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TypeScript Version: 3.0.0-dev.20180630
Search Terms: generic method, subclass, override, type parameter constraint
Code
class A {
m<T, U extends T>(t: T, u: U) { }
}
class B extends A {
m<T, U extends T>(t: T, u: U) { }
// ﹋ error
}
Expected behavior:
No errors; the m method in the subclass has exactly the same signature as the method it is overriding.
Actual behavior:
The compiler warns on the method override B.m:
Type '<T, U extends T>(t: T, u: U) => void' is not assignable
to type '<T, U extends T>(t: T, u: U) => void'.
Two different types with this name exist, but they are unrelated.
Types of parameters 'u' and 'u' are incompatible.
Type 'U' is not assignable to type 'T'.
Type 'T' is not assignable to type 'T'.
Two different types with this name exist, but they are unrelated.
Note that even if you change the names of the type parameters in method B.m, as in:
class B extends A {
m<T2, U2 extends T2>(t: T2, u: U2) { }
}
you still get the error Type 'T' is not assignable to type 'T'. Two different types with this name exist, but they are unrelated.
If you remove the extends T generic constraint, it compiles.
Playground Link:
here
Related Issues:
Nothing obviously related; #23960 maybe?
So, is this a compiler bug? Or is it intended, and if so, what's the reasoning for it? This issue is inspired by a Stack Overflow question that left me scratching my head.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the reported example in the TypeScript playground or a compiler test, using generic methods with a constrained type parameter in a subclass. Trace the override compatibility check for the two method signatures and add a regression test showing that the equivalent override is accepted while the constraint remains enforced.
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