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
Search Terms: Strict tuple, stricter tuples, tuple type narrowing, tuple union type, conditional tuple
Code
typex=[string]typey=[string,number]typez=x|yfunctionf(arg: z){if(arg[1]!==undefined){constresult=arg// z; should be yconstfirst=result[1]// string | number; should be numberreturnfirst}else{returnundefined}}
Expected behavior:
I would expect the type system to narrow the types based on unions of tuples.
I should also mention that this also doesn't work for "tagged" tuple unions either.
typex=["x"]typey=["y",number]typez=x|yfunctionf(arg: z){if(arg[0]==="x"){constresult=arg// z; should be yconstfirst=result[1]// string | number; should be numberreturnfirst}else{returnundefined}}
Nice, but that won't cover a situation where you have multiple tuples of the same length. It also doesn't work with a simply typeof check.
typew=[number,string]typex=[string]typey=[string,number]typez=x|yfunctionf(arg: z){if(typeofarg[1]==="number"){constresult=arg// z; should be yconstfirst=result[1]// string | number; should be numberreturnfirst}else{returnundefined}}
Activity
ccorcos commentedon Apr 18, 2018
I should also mention that this also doesn't work for "tagged" tuple unions either.
ccorcos commentedon Apr 18, 2018
Bonus: I could be wrong, but if you could do this and were to use enums, you basically have GADTs in Typescript 👍
ccorcos commentedon Apr 18, 2018
I'm creating some functions to work around this issue and I'm getting some issues using function overloads as well.
ccorcos commentedon Apr 18, 2018
Similar issue, but this is more precisely the one I'm dealing with in my code.
RyanCavanaugh commentedon Aug 22, 2018
You can do this now by testing for
arg.length === 2We could potentially add e.g.
arr[7] === undefinedas a special type guard for tuples. Is checking the length instead a good solution for you?ccorcos commentedon Aug 22, 2018
Nice, but that won't cover a situation where you have multiple tuples of the same length. It also doesn't work with a simply typeof check.
playground
RyanCavanaugh commentedon Aug 22, 2018
Actually #26424 should fix this
RyanCavanaugh commentedon Aug 22, 2018
#10530
nikeee commentedon Apr 3, 2020
I have a silimar related issue. Is there any reason TS cannot narrow the tuple types in this case?
Tested in playground's "Nightly" compiler.