This page looks best with JavaScript enabled

Typing collections in Typescript

 ·   ·  ☕ 2 min read

How are collections typed in Typescript?

Primitives are fairly easy to type - we have seen this while discussing Typescript and its types.

1
2
const num: number = 0;
const msg: string = "hello";

We have seen examples of typed arrays in the same post, but how about all the other collections? How far down the typed rabbit hole are you willing to go?

Arrays

There are two useful notations - pick one, or both.

1
2
let num: number[] = [1, 2, 3];
const numToo: Array<number> = [1, 2, 3];

Tuples

Tuples, unlike arrays, have fixed number of elements. In Typescript, we just go about typing all of them.

1
const life: [string, number] = ["everything", 42];

Objects

Keys can have their own types in Typescript Objects.

1
2
3
4
const planet: { name: string, position: number } = {
  name: "earth",
  position: 3
};

You can use objects to instantiate the class..

1
2
3
4
5
6
class Planet {
  constructor(public name: string, public position: number) {}
}

const earth = new Planet("earth", 3);

Map

Just like Javascript, a map is an object that stores a key-value pair.

1
2
3
4
5
6
const planet = new Map<string, string>();
planet.set("name", "earth");
planet.set("position", "1");

console.log(planet);
// Map { 'name' => 'earth', 'position' => '1' }

The key and value can have any type - we just happen to use strings for both.

Set

A set is an ordered list of values with no duplicates.

1
2
3
4
5
const planet = new Set<string>();
planet.add("earth");

console.log(planet);
// Set { 'earth' }

WeakMap and WeakSet

WeakMap and WeakSet behave like their strong counterparts, but with an object for key. They very much resemble what they can do in Javascript but with types.

Consider this example for WeakMap..

1
2
const planet = new WeakMap<{ bodyType: string }, string>();
planet.set({ bodyType: "planet" }, "earth");

.. and, for the WeakSet.

1
2
3

const planet = new WeakSet<{ name: string }>();
planet.add({ name: "earth" });
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things