Skip to content

Bug in arrays map return type #35

Closed
@n1kk

Description

@n1kk

The return type for the map method in Array and ReadonlyArray seems to be causing some trouble.

  map<U, This = undefined>(
    callbackfn: (this: This, value: T, index: number, array: this) => U,
    thisArg?: This
  ): { [K in keyof this]: U };

In case when it is an instance of the class that extends the Array it will change all the keys of the class to the mapped value type, including methods and public fields.

class ArrX extends Array<number> {
  constructor(nums: number[]) {
    super(...nums);
  }

  sum(): number {
    return this.reduce((s, n) => s + n, 0);
  }
}

let arrX = new ArrX([2, 3, 4]);

let mapped = arrX.map((v) => v + 1);
let mapped: {
    [x: number]: number;
    sum: number;
    length: number;
    toString: number;
    toLocaleString: number;
    pop: number;
    push: number;
    concat: number;
    join: number;
    reverse: number;
    shift: number;
    slice: number;
    sort: number;
    ... 19 more ...;
    readonly [Symbol.unscopables]: number;
}

CodeSandbox playground link

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions