This page looks best with JavaScript enabled

Interfaces for Arrays in Typescript

 ·   ·  ☕ 2 min read

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.

1
2
3
4
5
6
7
8
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?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things