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?
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.
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' }] };
Array.from() The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.
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.
It is a method that can be polyfilled.
Language features that can't be polyfilled are transpiled (if possible on the selected TypeScript target).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With