0

I tried to use TypeScript built-in interface, ArrayLike, but still got the error message like following:

Error:(12, 11) TS2420: Class 'Point' incorrectly implements interface 'ArrayLike'. Index signature is missing in type 'Point'.

interface ArrayLike<T> {
    length: number;
    [n: number]: T;
}

class Point implements ArrayLike<number> {
    [0]: number = 10;
    length: number = 1;
}

How can I solve this problem? (or any workaround?)

2 Answers2

0

If you want your Point to be an array then why not just extending the Array class?

class Point extends Array<number> {
    // add Point array methods here
}

This way Point will implement the ArrayLike<number> interface automatically.

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
  • Fyi, http://stackoverflow.com/questions/26700164/extending-array-with-es6-classes#28224044 – Paleo Jul 11 '16 at 15:37
  • @Paleo Interesting, though I still haven't encountered any issues with extending the `Array` class. Also, why would you want to set the length of the array directly? It makes little sense. – Nitzan Tomer Jul 11 '16 at 15:44
  • Sincerely, I don't know why to use the interface `ArrayLike`. I just answered to the question. :s – Paleo Jul 11 '16 at 15:45
  • @Paleo I don't want to inherit all methods in Array due to the responsibility of the class. – DaeSeon Jeong Jul 12 '16 at 09:36
0

How to implement the interface ArrayLike:

class Point implements ArrayLike<number> {
    [n: number]: number;
    length: number = 1;
    [0]: number = 10;
}

let p = new Point()
p[23] = 34; // ok
p[23] = "34"; // Error: Type 'string' is not assignable to type 'number'
Paleo
  • 21,831
  • 4
  • 65
  • 76
  • Am I correct that in your answer `[n: number]: number;` is not required? So the correct implementation is `class Point implements ArrayLike { length: number = 1; [0]: number = 10; }` – Manu Chadha Jan 18 '19 at 21:44