Typing collections in Typescript

How are collections typed in Typescript?

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

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?


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

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


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

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


Keys can have their own types in Typescript Objects.

const planet: { name: string, position: number } = {
  name: "earth",
  position: 3

You can use objects to instantiate the class..

class Planet {
  constructor(public name: string, public position: number) {}

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


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

const planet = new Map<string, string>();
planet.set("name", "earth");
planet.set("position", "1");

// Map { 'name' => 'earth', 'position' => '1' }

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


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

const planet = new Set<string>();

// 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..

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

.. and, for the WeakSet.

const planet = new WeakSet<{ name: string }>();
planet.add({ name: "earth" });
comments powered by Disqus