Contextual type doesn't apply to elements of array literal spread into another array literal #45600
Labels
Bug
A bug in TypeScript
Domain: Contextual Types
The issue relates to contextual types
Effort: Moderate
Requires experience with the TypeScript codebase, but feasible. Harder than "Effort: Casual".
Help Wanted
You can do this
Milestone
Bug Report
π Search Terms
spread operator, type inference
π Version & Regression Information
β― Playground Link
Playground link with relevant code
π» Code
Workbench Repro
π Actual behavior
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 offield
in those objects becomesstring
(and is not detected to be'a' | 'b' | 'c'
which I specified in the interface), and a rather cryptic type error is shown: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:
Which forces the inferred types of the objects to actually be compatible, or assigning the spread array to a variable with an explicitly defined type:
π Expected behavior
I would expect the type of
expr3
in[expr1, expr2, ...expr3]
to be inferred to beIterable<T>
or something like that provided that we know that the type of elements of the overall array isT
. I believe that in my repro it would make types of nested objects to be inferred correctly asTest
.The text was updated successfully, but these errors were encountered: