-
Notifications
You must be signed in to change notification settings - Fork 12.8k
(Indirect) inference of array element type in callback function type does not work #40743
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
It’s incredibly difficult to understand/explain why, but this is basically working as intended. In fact, we believe that your workaround example maybe shouldn’t work if we wanted to be totally safe. The TL;DR is I think your code is safe in practice, but only because of constraints that the compiler can’t/doesn’t track. The more abstract patterns the compiler sees here are not safe in general. The proper solution is to replace The longer, more complicated answer, is that the |
Thank you very much for this comprehensive explanation. Indeed, I forgot about the T[number] syntax, I will give that a try in my code. |
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
TypeScript Version: 4.0.2
Search Terms: array element type inference callback
Code
Found a problem with type inference when tried to implement functions and array methods taking callbacks, where the array element type will be inferred from the actual array type.
What I have:
ElemT
that extracts the element type from an array type.FuncT
to be used in array iteration functions.The callback wants to pass the array with its actual type as parameter. Therefore,
FuncT
needs the array type as generic parameter, and must infer the element type for its first parameter.However, I fond a workaround: When I bake the
ElemT
into theFuncT
it works as expected. But that's a little inconvenient because this has to be done for multiple callback types in my real code.Expected behavior:
In
MyArr#example
,ElemType<this>
resolves toT
.Actual behavior:
In
MyArr#example
,this[0]
(with typeT
) cannot be assigned toElemT<this>
.Playground Link:
https://www.typescriptlang.org/play?#code/PTAEAsFMBsAdIE6gC4E94oPagJYDsAzRUGSAW0j2RXUlAIUzNAEMEEXUb4AoNDAKLRyAFQA8AQREkAHskoATAM6s8qANoBdAHygAvKCmz5eZaAAU+IkhEBKLaAD8oaQC5QeSADdEAbh48IKAAxizQ0ABGLMEA1vQArnjByDiYeCgsMfgA5iTCFFTcdCymrOycRXy0oABiicHiRpByiiolGjr6Fl7uQqKSItoANKzuUrb6ul6YOAr+gWDZ0JhR0AlJKWk8BPWb6c0sZLDCA8atqh3a5mwIYyIjwRHudUmNgxMA3jygPyER1+x1AAGTQjG62XygIJiPSwgwAd0wCBiSh4AF8AkFgtAWEoVBRkOBMAoeNjcSoALKoCTsMSDM6mFQ0jioOm6L6-UCweIRaA4YKyQ7HSDmR7PeriQk4JTaT7fTm-R7mKVKYGglDgaUQqFgGFw+gsHDQVGcjEYoA
The text was updated successfully, but these errors were encountered: