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 Answers 2

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Am I correct that in your answer [n: number]: number; is not required? So the correct implementation is class Point implements ArrayLike<number> { length: number = 1; [0]: number = 10; }
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.

4 Comments

@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.
Sincerely, I don't know why to use the interface ArrayLike<T>. I just answered to the question. :s
@Paleo I don't want to inherit all methods in Array due to the responsibility of the class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.