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
}
The polyfill code in MDN.
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.
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