Logo

How to declare and initialize a Dictionary in Typescript?

In TypeScript, you can declare a dictionary (an object keyed by strings, for example) by using an index signature or a Record type. Then you can initialize it with key-value pairs. Below are common approaches:

1. Using an Index Signature

interface MyDictionary { [key: string]: number; // or any type } const dict: MyDictionary = { apple: 1, banana: 2, }; dict["cherry"] = 3; // or dict.cherry = 3;

Explanation

  • [key: string]: number; means any string key is allowed, and the value must be a number.
  • You can read or write entries with dict[key].

2. Using Record<Keys, Value>

const dict: Record<string, number> = { apple: 1, banana: 2, }; // Add or modify entries dict["cherry"] = 3;

Explanation

  • Record<string, number> is a built-in generic type that means “an object with string keys and number values.”
  • This is equivalent to { [key: string]: number }, but more idiomatic for some codebases.

3. Declaring a Specific Dictionary of Known Keys

If your keys are fixed as 'apple' | 'banana' | 'cherry':

type FruitKey = "apple" | "banana" | "cherry"; const fruitCounts: Record<FruitKey, number> = { apple: 10, banana: 5, cherry: 8, };
  • This ensures you cannot add extra keys outside 'apple' | 'banana' | 'cherry'.

4. Summary

  • Index Signature:

    interface MyDictionary { [key: string]: SomeType; }

    or

    type MyDictionary = { [key: string]: SomeType };
  • Record<KeyType, ValueType>: A built-in generic approach, e.g. Record<string, number>.

These let you declare dictionary-like objects in TypeScript with type safety. Then you can initialize them with literal objects or populate them dynamically.

Also, to strengthen your JavaScript fundamentals (which TypeScript builds upon), check out the Grokking JavaScript Fundamentals course by DesignGurus.io. It covers core JS topics like prototypes, closures, and async patterns—helping you better utilize TypeScript’s features, including dictionary types.

CONTRIBUTOR
TechGrind