TypeScript | Array.from | error TS2339: Property 'from' does not exist on type 'ArrayConstructor'
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.
Edit
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.
2nd edit
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.