Dominik Marciniszyn

Backend Developer

Apr 10, 2020 in Development

Dictionary in TypeScript

Few weeks ago I was working on a task that was to rewrite the service from JavaScript to TypeScript. It was very challenging for me. I spent a lot of time to find the differences between those two languages. I work with great software developers therefore I was sure I would get good feedback. While working on this task I found an interesting case and I would like to tell you about it.

Dictionaries in JS

As it is known there is no dictionary in JavaScript but it is really easy to create and use a data type similar to dictionary. I would like to show you a fragment of code:

let dictionary = {
  firstname: 'Jack',
  lastname: 'Sparrow'
};

As you can see in example below, operations on the dictionary aren't very complicated:

// adding new value to dictionary
dictionary.age = 50;

// modyfing existing one
dictionary.firstname = 'John';

I wanted to created something that will be more like type, so I wrote my own dictionary type in TypeScript.

Implementation of dictionary type in TS

I started from defining the interface IKeyCollection. I wrote simple consrtuction with few methods.

export interface IKeyCollection<T> {
  add(key: string, value: T);
  containsKey(key: string): boolean;
  size(): number;
  getItem(key: string): T;
  removeItem(key: string): T;
  getKeys(): string[];
  values(): T[];
}

This is a generic interface. It means that under T you can put any type you want. For example it could be a number, a string or even more complex construction like an object. In the example below I want to show you my implementation of the interface for dictionary.

export default class Dictionary<T> implements IKeyCollection<T> {
  private items: { [index: string]: T } = {};
  private count: number = 0;

  add(key: string, value: T) {
    if (!this.items.hasOwnProperty(key)) {
      this.count++;
    }

    this.items[key] = value;
  }

  containsKey(key: string): boolean {
    return this.items.hasOwnProperty(key);
  }

  size(): number {
    return this.count;
  }

  getItem(key: string): T {
    return this.items[key];
  }

  removeItem(key: string): T {
    let value = this.items[key];

    delete this.items[key];
    this.count--;

    return value;
  }

  getKeys(): string[] {
    let keySet: string[] = [];

    for (let property in this.items) {
      if (this.items.hasOwnProperty(property)) {
        keySet.push(property);
      }
    }

    return keySet;
  }

  values(): T[] {
    let values: T[] = [];

    for (let property in this.items) {
      if (this.items.hasOwnProperty(property)) {
        values.push(this.items[property]);
      }
    }

    return values;
  }
}

Now we can use this implementation in our code:

let personHobbies = new Dictionary<string>();

personHobbies.add('jack', 'swimming');
personHobbies.add('mary', 'singing');
personHobbies.add('tom', 'dancing');

const keys = personHobbies.getKeys(); // will return ['jack', 'mary', 'tom']
const values = personHobbies.values(); // will return ['swimming', 'singing', 'dancing']

Summary

This kind of simple implementation can make your code more readable. By adding meaningful key name we can easily work on the data in dictionary. I decided to share my work with you because it is very important for developers to write the easiest and most readable code. My implementation is just an example. That is why I encourage you to try to implement your own solutions. Have fun and see you in the next article.

Do you need more information about this topic?

Schedule a call with our developers

Let's talk!

Back to top