Read Anthropic’s case study about Graphite Reviewer

TypeScript dictionary

Kenny DuMez
Kenny DuMez
Graphite software engineer

In TypeScript, a dictionary is a data structure that stores elements as key-value pairs, where keys are unique. This structure is essential for scenarios where you need to access data quickly based on custom keys. Although TypeScript doesn't have a built-in 'Dictionary' type like some other languages, you can use an dictionary-like object or a Map to replicate this functionality. This guide will explore how to implement and manipulate dictionaries in TypeScript, covering several key operations and best practices.

The simplest way to create a dictionary in TypeScript is by using an object. Here’s how you can define and initialize a dictionary using an object:

Terminal
interface Dictionary<T> {
[key: string]: T
}
let userAges: Dictionary<number> = {
John: 30,
Alice: 25,
Mark: 32
}

In this example, Dictionary<T> is a generic interface where T can be any type, allowing for type-safe access to the dictionary values.

TypeScript also supports Map, a collection introduced in ES6, which provides better performance for frequent additions and deletions:

Terminal
let userAges: Map<string, number> = new Map([
['John', 30],
['Alice', 25],
['Mark', 32]
])

A Map maintains the order of elements and includes several useful methods which facilitate easy manipulation of data.

To check if a key exists in a dictionary:

  • Using a dictionary-like object:

    Terminal
    if ('John' in userAges) {
    console.log('John is in the dictionary.')
    }
  • Using a Map:

    Terminal
    if (userAges.has('John')) {
    console.log('John is in the dictionary.')
    }

To add an element to a dictionary:

  • Using a dictionary-like object:

    Terminal
    userAges['Lisa'] = 28
  • Using a Map:

    Terminal
    userAges.set('Lisa', 28)

To iterate over a dictionary:

  • Using a dictionary-like object:

    Terminal
    for (let key in userAges) {
    if (userAges.hasOwnProperty(key)) {
    console.log(`${key}: ${userAges[key]}`)
    }
    }
  • Using a Map:

    Terminal
    userAges.forEach((value, key) => {
    console.log(`${key}: ${value}`)
    })
  • Using a dictionary-like object:

    Terminal
    delete userAges['Mark']
  • Using a Map:

    Terminal
    userAges.delete('Mark')
  • Using a dictionary-like object:

    Terminal
    const keys = Object.keys(userAges)
    const values = Object.values(userAges)
  • Using a Map:

    Terminal
    const keys = Array.from(userAges.keys())
    const values = Array.from(userAges.values())
  1. Choose the right type: Use Map for better performance and more built-in methods, especially if elements are frequently added or removed. Use objects for simpler or more static dictionaries.
  2. Type safety: Always define types for keys and values in your dictionaries to take full advantage of TypeScript’s type-checking.
  3. Avoid using any: Using any defeats the purpose of TypeScript’s type safety. Define interfaces or types where possible.
  4. Null checks: When accessing dictionary values, consider potential undefined or null values to avoid runtime errors.

Dictionaries in TypeScript, whether implemented with simple objects or the more robust Map type, are powerful tools for managing collections of key-value pairs. By understanding and utilizing the appropriate methods and best practices, you can effectively manage and manipulate dictionaries in your TypeScript applications. This enables clearer, more maintainable, and efficient code that leverages TypeScript's full capabilities.

Graphite
Git stacked on GitHub

Stacked pull requests are easier to read, easier to write, and easier to manage.
Teams that stack ship better software, faster.

Or install our CLI.
Product Screenshot 1
Product Screenshot 2