-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Array spreads should be contextually typed #42037
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
I think that issue is not quite related. This seems pretty reasonable, though in the future please follow the template. const a: ("foo" | "bar")[] = [
...(Math.random() < 0.5 ? ["foo"] : []),
]; |
Yeah sorry - I used the "reference in new issue" button and it pre-filled the above quote instead of the standard template, so I just went with that. |
I guess object spread types are inferred in a way analogous to the way in which the array example isn't, so here's another example.
|
Any updates on this case? type Case = [string?]
const caseTrue: Case = [...(true ? ["abc" ] : [])];
const caseFalse: Case = [...(false ? ["abc"] : [])]; |
TypeScript Version: 3.8
Search Terms:
Response to Original Issue Post
If you post a more representative sample where it's not just spreading for the sake of spreading, we may be able to advise more.
Originally posted by @RyanCavanaugh in #30761 (comment)
Real Use Case
The common pattern of literal array assignment with conditional inclusion of elements is one use case.
Code
The error messages given above are both
Type 'string[]' is not assignable to type '"a"[]'
.Of course if the type of the nested array is asserted or otherwise known, the spread doesn't get in the way of that - it only seems to interrupt the automatic inference of the literal. We get as specific as
string
, but not as specific as the actual value.The text was updated successfully, but these errors were encountered: