Skip to content

Instantly share code, notes, and snippets.

@mrdziuban
Last active January 13, 2017 17:55
Show Gist options
  • Save mrdziuban/837c9d297a155ef2d98071d6df5a2065 to your computer and use it in GitHub Desktop.
Save mrdziuban/837c9d297a155ef2d98071d6df5a2065 to your computer and use it in GitHub Desktop.
TypeScript spread operators

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]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment