Search Terms: Array type
Code
Simplest code:
var a: string[] = ['a'];
var shouldBeString = a[0] // string
var couldBeString = a[10000]; // string
var notAString = a[Infinity]; // string
var alsoNotAString = a[NaN]; // string
I get the difficulty in discerning 0, 10, NaN and Infinity since the type of all those is number.. but wouldn't it make sense then to make the return type from these queries string | undefined?
For those who don't want that they can turn off strictNullChecks
Tuples are only slightly better
// tuple
var str = '';
var aa = [str, str] as const
var _shouldBeString = aa[0] //string
var _notString1 = aa[10000]; // type error
var _notString2 = aa[Infinity]; // no error
var _notString3 = aa[NaN]; // no error
Expected behavior:
var arr = [''];
var item = arr[10];
// typeof item = string | undefined;
Actual behavior:
var arr = [''];
var item = arr[10];
// typeof item = string;
Playground Link:
TS-Playground
Related Issues:
Duplicate of #13778.
Duplicate #13778
@MartinJohns easy dupe day eh
@RyanCavanaugh I spend way too much time reading these issues in this repository, for quite some time already (using TypeScript since preview version), so I often recognize repeated issues. Just sometimes I fail to find the original issue.
@RyanCavanaugh @MartinJohns
Fine, yes part one complete overlap..
However I did not see this tuple behavior being address in the other thread.. Can't see how those arguments would apply here:
// tuple
var str = '';
var aa = [str, str] as const
var _shouldBeString = aa[0] //string
var _notString1 = aa[10000]; // type error
var _notString2 = aa[Infinity]; // no error, type string
var _notString3 = aa[NaN]; // no error, type string
Infinity and NaN aren't specially typed; they're just number. See #32277 and #28682
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.
Most helpful comment
@MartinJohns easy dupe day eh