Manu Chadha
Manu Chadha

Reputation: 16729

Unable to understand ArrayLike interface in Typescript

I recently found about ArrayLike interface

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

I am struggling to understand what [n:number]:T means. Is this declaring an array of type T and the size of the array is n?

Upvotes: 8

Views: 5666

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

It's an index signature. An object can be indexed using a string or a number in typescript (ie o[0] or o['prop']).

This is telling the compiler that we can use a number to index into an object of type ArrayLike<T> and that the indexer will return a T. The name of the index parameter (n in this case) does not have much relevance except for documentation purposes.

See here and here and here for more information.

Upvotes: 11

Related Questions