TypeScript | Array.from | error TS2339: property 'from' does not exist in type 'ArrayConstructor'

I was googling, but I can not find information on what and how to add to my project to allow me to use ES6 methods such as Array.from

__ EDIT: remote prototype word

+17
ecmascript-6 typescript
source share
3 answers

You can easily extend existing types as follows:

 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 as you require.
But it can be done like this:

 interface ArrayConstructor { from(arrayLike: any, mapFn?, thisArg?): Array<any>; } 

Then you can use Array.from .

Try it on ; } var a: any [] = Array.from ([1,2,3]); rel = noreferrer> playground .


edit

If you need to fill out an implementation (since the environment in which you are going to work does not have one), then here's how:

 interface ArrayConstructor { from(arrayLike: any, mapFn?, thisArg?): Array<any>; } Array.from = function(arrayLike: any, mapFn?, thisArg?): Array<any> { // place code from MDN here } 

Polyfill code in MDN .


2nd editing

Based on the comment, I add 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>; } 

This is an exact copy of how it is defined in lib.es6.d.ts.

+10
source share

If you are sure that the API exists on your engine at runtime, compile with --lib es6 (or --lib dom,es6 if you use the DOM API).

See the Compiler Options documentation for more details.

+13
source share

I hope this is not very off topic, but I found this when refactoring js to ts, and if you have a similar array, it seems to work just by passing the array as to the constructor instead of using from, eliminating the need for an additional method .

eg

 // someScript.js Array.from( arrayLikeThing ); 

becomes

 // someScript.ts Array( arrayLikeThing ); 

If there are other reasons to continue using .from, then the above answers are excellent.

-one
source share

All Articles