Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript | Array.from | error TS2339: Property 'from' does not exist on type 'ArrayConstructor'

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

like image 868
Kania Avatar asked Apr 19 '16 09:04

Kania


2 Answers

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.

like image 135
mohamed hegazy Avatar answered Oct 31 '22 22:10

mohamed hegazy


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.

like image 11
Nitzan Tomer Avatar answered Oct 31 '22 23:10

Nitzan Tomer