You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Contextual type doesn't apply to elements of array literal spread into another array literalΒ #45600
The types of objects in the array nested through the spread operator is not inferred to be Test, as such inference begins from scratch, so the type of field in those objects becomes string (and is not detected to be 'a' | 'b' | 'c' which I specified in the interface), and a rather cryptic type error is shown:
Type '{ field: string; }' is not assignable to type 'Test'.
Types of property 'field' are incompatible.
Type 'string' is not assignable to type '"a" | "b" | "c"'.
I have also included an example with using the spread operator in a function call for completeness, it generates basically the same error.
I'm not sure if this is really a bug, but regardless, it is trivial to work around by just forcing compiler's hand a little by doing this:
I would expect the type of expr3 in [expr1, expr2, ...expr3] to be inferred to be Iterable<T> or something like that provided that we know that the type of elements of the overall array is T. I believe that in my repro it would make types of nested objects to be inferred correctly as Test.
changed the title [-]Type inference starts all over again for array literals passed to the spread operator[/-][+]Contextual type doesn't apply to elements of array literal spread into another array literal[/+]on Aug 27, 2021
Can you show an example of why you'd use a pattern like this in real life? It doesn't seem useful to apply an array spread to an array literal, but I'm sure I'm missing something.
Activity
[-]Type inference starts all over again for array literals passed to the spread operator[/-][+]Contextual type doesn't apply to elements of array literal spread into another array literal[/+]andrewbranch commentedon Aug 27, 2021
Can you show an example of why you'd use a pattern like this in real life? It doesn't seem useful to apply an array spread to an array literal, but I'm sure I'm missing something.
Andarist commentedon Feb 4, 2023
as to the real-life use case - conditional spreading comes to mind: