Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Array.from in IE11

Array.from is an ES6 feature. When I use it in TypeScript and compile to ES5 target it does not change it:

tsc -t es5 prog.ts

i.e. when I look inside prog.js I still see Array.from in the same place. Using prog.js in IE11 complains as follows:

Object doesn't support property or method 'from'

Why doesn't TypeScript convert Array.from in to some ES5 alternative?

Is there a way to set it up so it does?

like image 496
chriskelly Avatar asked Apr 14 '16 12:04

chriskelly


People also ask

What is the use of array from?

The Array. from() method is used to create a new array instance from a given array. In the case of a string, every alphabet of the string is converted to an element of the new array instance and in the case of integer values, a new array instance simply takes the elements of the given array.

How do you access an array of objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };

What is array from in JS?

Array.from() The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.

How do I push one array into another?

If your arrays are not huge, you can use the push() method of the array to which you want to add values. The push() method can take multiple parameters so you can use the apply() method to pass the array to be pushed as a collection of function parameters. let newArray = []; newArray.


2 Answers

It is a method that can be polyfilled.

Language features that can't be polyfilled are transpiled (if possible on the selected TypeScript target).

like image 96
Estus Flask Avatar answered Oct 16 '22 12:10

Estus Flask


I would recommend using core-js as you'll get many more polyfills and won't have to polyfill APIs piecemeal. If all you need/want is Array.from, then by all means rip it from the MDN site, but you can selectively import just the polyfills you need using core-js.

Using npm to install core-js...

> npm install --save core-js

...then in your .ts...

import 'core-js' // to get the whole thing

or

import 'core-js/es/array'; // to get just array polyfills for example
like image 12
Eric Lease Avatar answered Oct 16 '22 12:10

Eric Lease