π Search Terms
"infer"
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play?ts=5.5.0-dev.20240404#code/KYDwDg9gTgLgBAYwDYEMDOa4BVhpgHgEEAaOAIQD44BvAKDgcQgDs8oBXBGaOACjHYAjJAEsEcFAC44JOAOFi4g6WQCUNAL616jGLgIBhCrwTSDq6Tjz4ypIzR2NGUYDHZRmcZsADu2fbwwABYiaAB0gqQIqgDcjnBaWkA
π» Code
export class Test<A, B> {
constructor (public a: A, public b: B) {}
test<C>(c: C): Test<B, C> {
return new Test(this.b, c);
}
}
π Actual behavior
The invocation of new Test infers generic parameters of <C, C>, even though this.b is B and c is C, which should pretty clearly result in <B, C>. This incorrect inference causes an error on return since it does not match the return type annotation:
Type 'Test<C, C>' is not assignable to type 'Test<B, C>'.
Type 'C' is not assignable to type 'B'.
'B' could be instantiated with an arbitrary type which could be unrelated to 'C'.(2322)
Explicitly invoking new Test<B, C> compiles without error.
π Expected behavior
Compiles successfully.
Additional information about the issue
I initially posted this with a slightly more complex example, where the second argument to both Testβs constructor and the test method was a callback, (v: A) => B and (v: B) => C, respectively. I realized that this callback was a bit of a red herring and the bug occurs even when these are simple, explicitly-annotated values.
π Search Terms
"infer"
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play?ts=5.5.0-dev.20240404#code/KYDwDg9gTgLgBAYwDYEMDOa4BVhpgHgEEAaOAIQD44BvAKDgcQgDs8oBXBGaOACjHYAjJAEsEcFAC44JOAOFi4g6WQCUNAL616jGLgIBhCrwTSDq6Tjz4ypIzR2NGUYDHZRmcZsADu2fbwwABYiaAB0gqQIqgDcjnBaWkA
π» Code
π Actual behavior
The invocation of
new Testinfers generic parameters of<C, C>, even thoughthis.bisBandcisC, which should pretty clearly result in<B, C>. This incorrect inference causes an error onreturnsince it does not match the return type annotation:Explicitly invoking
new Test<B, C>compiles without error.π Expected behavior
Compiles successfully.
Additional information about the issue
I initially posted this with a slightly more complex example, where the second argument to both
Testβsconstructorand thetestmethod was a callback,(v: A) => Band(v: B) => C, respectively. I realized that this callback was a bit of a red herring and the bug occurs even when these are simple, explicitly-annotated values.