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
{{ message }}
Repository navigation
Type of tuple element not inferred correctly when using const variable as index #10186
enumIdx{Zero}constidxZero=0;typeTup=[string,number];constt: Tup=["5",3];constel1=t[0];// inferred type: stringconstel2=t[idxZero];// inferred type: string | number, should be stringconstel3=t[Idx.Zero];// inferred type: string | number, should be string
Expected behavior:
Type of el1, el2, el3 inferred by TypeScript should be string (same as type of first element of Tup).
Actual behavior:
Type of el1 is correctly inferred but type of el2 and el3 is not (it's inferred as string | number i.e. a union of all unique types of Tup type.
I understand that if an index can be an arbitrary value, that's the best TypeScript can do, but idxZero and Idx.Zero are constants and TypeScript should pick up on that.
This came up when trying to type a real-life code where for performance I send data from the server as array of arrays (vs. more verbose array of objects). I try to represent that as a tuple in TypeScript and have symbolic names for indexes into that tuple (as const idxFoo = 0 etc.), but using those symbolic names to index the tuple makes the result incorrectly typed.
Activity
mhegazy commentedon Apr 27, 2017
This should be working as intended in latest.