Microsoft/TypeScript
GitHub ã§èŠãCovariant generic parameters fail unification
Open
#61,503 opened on 2025幎3æ28æ¥
BugDomain: check: Type InferenceHelp Wanted
Repository metrics
- Stars
- Â (48,455 stars)
- PR merge metrics
-  (å¹³åããŒãž 6d 17h) (30d ã§ 9 merged PRs)
説æ
ð Search Terms
"contravariant", "unification"
ð Version & Regression Information
- This changed between versions 3.3.3 and 3.5.1
⯠Playground Link
ð» Code
const contravariant = () => {
const combine = <Ctx>(_1: (c:Ctx) => null, _2: (c:Ctx) => null): () => Ctx => () => undefined as any;
const less_constrined = <C extends {length:number}>(c: C): null => null;
const more_constrined = <C extends {length:number, charCodeAt(_:number):number}>(c: C): null => null;
const test1 = combine(less_constrined, more_constrined);
const test2 = combine(more_constrined, less_constrined);
}
const covariant = () => {
const combine = <Ctx>(_1: () => Ctx, _2: () => Ctx): Ctx => undefined as any;
const less_constrined = <C extends {length:number}>(): C => undefined as any;
const more_constrined = <C extends {length:number, charCodeAt(_:number):number}>(): C => undefined as any;
const test1 = combine(less_constrined, more_constrined);
const test2 = combine(more_constrined, less_constrined);
}
ð Actual behavior
In the contravariant example the type is inferred from the first argument, so test1 fails to typecheck, despite both test1 and test2 sharing the same argument types, just reversed. This is also different from the covariant case where types are properly unified in both test1 and test2
ð Expected behavior
The behaviour for the covariant and contravariant case should match, so test1 should be inferred as
<C extends { length: number; charCodeAt(_: number): number; }>() => C
Additional information about the issue
No response