-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Problems with inference in unions of tuples #21949
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
Ok, after investigating the playground example a little bit more I get what's going on. Type narrowing is being too aggressive (to my expectations anyway) and the compiler is narrowing This is not an implementation bug, but I think it's arguable whether it's a design bug, as it kind of makes futile the intent of having the tuple union in the first place. It probably depends on what that intention is, but there is no way of specifying that in the definition. The only fix (... I can think of so far...) is to cast at every access, which is kind of annoying. If I have to cast everywhere I use such a variable it's like not casting anywhere since the possibility of introducing a casting error somewhere defeats the purpose of typing. If narrowing is unavoidable, then it should probably narrow to '[string]' instead of 'string[]' |
Basically a duplicate of #5203. We know (from analyzing the code) that |
Depending on your use case, you could change type a = {0: string, 1?: never, length: 1} | {0: string, 1: number, length: 2} or type a = ([string] & {1?: never})| [string, number] |
Continuing with my argument from my last comment:
I tried it on the playground type g = [string];
const h = ["I'm back!"]; // inferred as string[]
const i: g = ["I'm back!"];
const j = h[1]; // j is inferred as string. Correct
const k = i[1]; // k is inferred as string. (mmmh...?)
// Shouldn't it be undefined after typescript 2.7? @RyanCavanaugh I just read your comments on #5203 but I must say, shouldn't |
@jcalz You're right, that would work. But after investigating on the playground a bit more (see my previous comments) and after the introduction of fixed length tuples in 2.7, I think there might actually be an implementation bug (not the one imagined in the OP) |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
Search Terms: tuples unions inference
In the following example, for constant
f
, the inferred type should benumber | undefined
(or even narrowed down toundefined
in this particularly obvious case) but instead it's being incorrectly inferred asstring
.I tried this on 2.8.0-dev.20180214 as well and it's still showing the same behavior.
Here's a playground link
The text was updated successfully, but these errors were encountered: