- read

Please use TS to write the declarations of 20 array methods

Xiuer Old 56

Photo by Markus Spiske on Unsplash

Step 1: Classify

It is a bit difficult to write 20 array methods in one breath. We can classify the array methods in our minds, and group the same type of operations into one category. Isn’t it easier to write this way?

  • Add element classes: push, unshift
  • Delete element classes: pop, shift, splice
  • Array to string class: toString, join
  • Traversal classes: forEach, reduce, reduceRight, map, filter, some, every
  • Sort:sort
  • Concatenation:concat
  • Index: indexOf, lastIndexOf

I wrote a full 19 in one breath, but it is not enough for the 20. It seems that I am not qualified to say “the front end is dead”. Let’s check what is wrong:

  • flip:reverse
  • Shallow copy: slice

Why write this? lib.es5.d.ts Because these are array methods defined in vscode

Step 2: Implement the array interface

The array needs to receive a generic parameter to dynamically obtain the element type in the array

interface MyArray<T> {


Step 3: Method definition

The first is the element adding class method: push, unshift, don’t forget that they have a return value, and the return value is the length of the new array

push(...args: T[]): number;
unshift(...args: T[]): number;

For deleting element class methods, the first two are easier to write. Their return values ​​are all the deleted elements. However, it should be noted that an empty array returns undefined after being called;

pop(): T | undefined;
shift(): T | undefined;
/**Wrong way of writing: splice(start: number, deleteNum: number, ...args: T[]): T[];**/

There is still a problem with splice writing like this, because only the first parameter of splice is mandatory, so you need to write multiple declarations

splice(start: number, deleteNum?: number): T[];
splice(start: number, deleteNum: number, ...args: T[]): T[];