Interfaces for Arrays in Typescript

What exactly are interfaces for arrays?

Previously we have seen interfaces as types. Interfaces provide useful abstraction on class and can be useful in tricky situations with complex types.

But, what about interfaces for array?

It turns out interfaces can be as easily applied for array types as well. They are just super useful as interfaces that define complex types and make arrays type-safe - nothing more, nothing less.

Interfaces can define type for both array and its values. Let’s see an example.

interface iPlanet {
  [index: number]: string;
}

const planets: iPlanet = ["earth", "mars", "mercury"];

console.log(planets);
// [ 'earth', 'mars', 'mercury' ]

Did I hear you say that you learnt this doing Javascript in kindergarten?

Well, yes - very much possible.

But, did you use a different type of index? How about layering the complexity with objects as values or for index?

interface iPlanet {
  [index: string]: iPlaPo;
}

interface iPlaPo {
  name: string;
  position: number;
}

let planets = new Array<iPlanet>();

planets["earth"] = { name: "earth", position: 3 };
planets["mars"] = { name: "mars", position: 4 };

console.log(planets);

/* output
[
  earth: { name: 'earth', position: 3 },
  mars: { name: 'mars', position: 4 }
]
*/

The example is not useful by itself. But you can quite imagine what it could be. Complicated data structures can be self-contained within arrays and subject to some sweet iterations.

comments powered by Disqus