microsoft / microsoft/TypeScript

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

Open
#10,886 4 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Domain: lib.d.ts Help Wanted Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in lib.es6.d.ts and inspect the Array method and static constructor declarations against the examples in the issue. Determine how return types should represent subclassing, map, and Symbol.species, then verify the provided MyArray and MyArray2 cases compile as intended.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.