I was googling, but cannot find the information what and how should I add to my project to allow me using ES6 methods like Array.from
__ EDIT: removed prototype word
I was googling, but cannot find the information what and how should I add to my project to allow me using ES6 methods like Array.from
__ EDIT: removed prototype word
If you are sure the API exists on your engine at runtime, compile with --lib es6 (or --lib dom,es6 if you are using the DOM APIs).
See Compiler Options documentation for more details.
You can easily extend existing types like so:
interface Array {
from(arrayLike: any, mapFn?, thisArg?): Array<any>;
}
The problem here is that this will add the function to the array instances and not as a static function like you require.
But that can be done like so:
interface ArrayConstructor {
from(arrayLike: any, mapFn?, thisArg?): Array<any>;
}
Then you should be able to use Array.from.
Try it out on Playground.
If you need to polyfill the implementation (because the environment in which you intend to run doesn't have it), then this is how:
interface ArrayConstructor {
from(arrayLike: any, mapFn?, thisArg?): Array<any>;
}
Array.from = function(arrayLike: any, mapFn?, thisArg?): Array<any> {
// place code from MDN here
}
Based on a comment, I'm adding a typed version:
interface ArrayConstructor {
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
from<T>(arrayLike: ArrayLike<T>): Array<T>;
}
It's an exact copy of how it's defined in the lib.es6.d.ts.
I hope it isnt terribly off topic but I found this while refactoring js to ts, and if you have an array like, it appears to work simply passing the array like to the constructor instead of using from, removing the need for the extra method.
eg
// someScript.js
Array.from( arrayLikeThing );
becomes
// someScript.ts
Array( arrayLikeThing );
If there are other reasons to maintain using .from then the above answers are great.
Array.from(Array(3)).map(v => 1) // [1, 1, 1]Array(Array(3)).map(v => 1) // [1]