Skip to content

Array inheritance in ES6 declaration file (lib.es6.d.ts) #10886

@ggmod

Description

@ggmod

ES6 supports Array inheritance, but this is not reflected in the TypeScript declaration file (lib.es6.d.ts).

Array functions like 'filter' and 'slice' return an array of the subclass, so the following should compile in TypeScript:

class MyArray extends Array {
    get size() { return this.length; }
}

var x = new MyArray(10).slice();
x.size;

The functions 'reverse', 'concat', 'slice', 'splice', 'filter' should return with the type 'this'.
The 'map' function returns an instance of the subtype too, but it I don't know how that could be represented in TypeScript, as it would require a generic parameter in the return type, something like:
map<U>(callback: (value: T, index: number, array: this) => U): this<U>

Another issue is the static constructors of the Array class, this should compile too:

var x = MyArray.of(1,2,3);
var y = MyArray.from([1,2,3]);
x.size;
y.size;

There are also some additional complications added by the @@species Symbol, which can be used to change the type signature of the subclass to not use 'this' as the return value for functions like 'filter' and 'slice'. So for the following example, the subclass would work how the return types are defined in the declaration file currently:

class MyArray2 extends Array {
    static get [Symbol.species]() { return Array; }
}

Chrome and Node.js both already implement the array inheritance features shown here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Domain: lib.d.tsThe issue relates to the different libraries shipped with TypeScriptHelp WantedYou can do thisSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions