Luke Skywalker Luke Skywalker - 1 month ago 9
TypeScript Question

Typescript -> ES5 issue

I write this in typescript:

const mask = [...Array(10)].map((item) => 0);


In the node console it produces a array of 10 zeros:

> [...Array(10)].map((item) => 0);
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]


Once transpilied in javascript, it produces:

var mask = Array(10).slice().map(function (item) { return 0; });


But this is not equivalent:

> Array(10).slice().map(function (item) { return 0; })
[ , , , , , , , , , ]


I was under the impression that typescript is supposed to produced iso-functional code. Was I wrong? Should I pay attention to everything TS is producing?

I am using node v7, tsc 1.20150623.0 with this config:

{
"compilerOptions": {
"emitDecoratorMetadata": true,
"module": "commonjs",
"target": "ES5",
"outDir": ".tmp/js",
"rootDir": "js"
}
}

Answer

This is a known and open issue with TypeScript that should be fixed in TypeScript 2.1.

The following code:

[...(new Array(5))]

translates into:

(new Array(5)).slice();

However, the ES6 meaning is not the same. See the output below:

> [...(new Array(5))]
[ undefined, undefined, undefined, undefined, undefined ]
> (new Array(5)).slice();
[ , , , ,  ]

Expected behavior:

Array.apply(null, Array(5))
Comments