The goal here is to create an array of [0, 1, 2, 3, 4]
. Every "Working ES6" column below accomplishes this. The first
example fails to compile in TypeScript. The second example compiles and works, but throws errors in IE. The third
example compiles, but does not achieve the desired functionality. The last example works as expected
(it was found in the comments of Microsoft/TypeScript#8856).
Working ES6 | TypeScript | Compiled JS | Result |
---|---|---|---|
[...Array(5).keys()] |
error TS2461: Type 'IterableIterator' is not an array type. | n/a | n/a |
Array.from(Array(5).keys()) |
Array.from(Array(5).keys()) |
Array.from(Array(5).keys()) |
[0, 1, 2, 3, 4] , but does not work in IE |
[...Array(5)].map((_, i) => i) |
[...Array(5)].map((_: any, i: number) => i) |
Array(5).slice().map(function (_, i) { return i; }) |
[undefined, undefined, undefined, undefined, undefined] |
Array.apply(null, Array(5)).map((_, i) => i) |
Array.apply(null, Array(5)).map((_: any, i: number) => i) |
Array.apply(null, Array(5)).map(function (_, i) { return i; }) |
[0, 1, 2, 3, 4] |