-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Infer a tuple type instead of array type when possible #44309
Comments
Related #32758 |
What's your rough definition of "possible" ? |
@RyanCavanaugh I don't have a strict definition. But for me, Another one that comes to mind is I'm more curious about why this isn't a feature in Typescript yet, and whether this is something that we can/should introduce. |
I'm not sure how to answer that; we have thousands of open suggestions, all which were opened by people who think they are good ideas and would like to have them 🙂 |
So for TypeScript, As an example of why this just isn't the default already, I wouldn't expect this code to be an error: const p = [1, 2, 3].map(n => -n);
p.push(-4); but it sounds like you're proposing that it should be (since |
Just for sake of exploration: that question is whether to have typescript infer the type of an array literal to be an
Either way, I'm fine with typescript inferring the type of I would, however, want this code to produce an error:
|
Hmm, if there's a hard technical limitation, then I would understand. I don't know anything about how Typescript is implemented underneath. |
It seems #11252 have fixed it, and it's status is "Merged". Is there any regression? |
@whzx5byb seems like there may have been a regression.
|
Suggestion
I'd prefer typescript to be more aggressive about inferring tuple types, instead of always defaulting to Array.
This is related to #6574. I'd like to open up a discussion about this again since that thread is locked, and conversation stopped after a workaround was provided without completely addressing the general issue.
🔍 Search Terms
Typescript, tuple, tuples, map, inference
✅ Viability Checklist
My suggestion meets these guidelines:
Existing typescript code could start emitting type errors from this change, so it would make sense to provide this as an option in tsconfig.
⭐ Suggestion
Typescript should infer a type to be a tuple instead of an array when it's possible.
📃 Motivating Example
The specific example I have in mind is for
Array.prototype.map()
, but there are probably more.Here, typescript infers the type of
result
to benumber[]
rather than[number, number, number]
. This could result in some wonkiness when trying to access values inside the tuple:Both of these errors can be caught if Typescript instead inferred
result
to be the tuple type[number, number, number]
.💻 Use Cases
The above example is a use case. I want typescript to tell me when I make errors in my code.
The text was updated successfully, but these errors were encountered: