TypeScript Dictionary – How to Create and Use

As a TypeScript developer, you should know how to work with TypeScript dictionaries. In this tutorial, I will explain everything about dictionaries in TypeScript such as declare a dictionary in TypeScript. With a few real examples, I will explain how to create and use a dictionary in TypeScript.

What is a Dictionary in TypeScript?

A dictionary in TypeScript is a data structure that stores values using unique keys, allowing you to quickly look up a value by its key. Although JavaScript objects can act as dictionaries, TypeScript adds type safety, helping you prevent bugs and write more reliable code.

Example:

Here is a simple example.

const phoneBook = {
  "Alice": "123-4567",
  "Bob": "987-6543"
};

Here, "Alice" and "Bob" are keys, and their phone numbers are the corresponding values.

Check out How to Initialize an Empty Dictionary in TypeScript

Declare a Dictionary in TypeScript

Now, I will show you how to declare a dictionary in TypeScript using various methods with examples.

1. Create a Basic TypeScript Dictionary

In TypeScript, you can define a dictionary using an interface with an index signature. This tells TypeScript that any string key will have a value of a specific type.

Example:

Here is an example:

interface Dictionary {
  [key: string]: string;
}

const phoneBook: Dictionary = {
  "Alice": "123-4567",
  "Bob": "987-6543"
};

You can see the exact output in the screenshot below:

typescript dictionary

You can also use numbers as keys:

interface NumberDictionary {
  [key: number]: string;
}

const codes: NumberDictionary = {
  1: "USA",
  44: "UK"
};

Here is another example of a TypeScript dictionary with string keys and string values.

let colors: { [key: string]: string } = {
  "red": "#FF0000",
  "green": "#00FF00",
  "blue": "#0000FF"
};
  • { [key: string]: string } means: “This is an object where each key is a string, and each value is a string.”
  • colors can have any number of string keys, each mapping to a string value.

Check out Convert Typescript Dictionary to String

2. Type Safety with Index Signatures

TypeScript enforces the types you specify in your dictionary, so you can’t accidentally store the wrong type of value.

The { [key: string]: valueType } syntax is called an index signature.

Let me show you an example.

Example:

interface Dictionary {
  [key: string]: string;
}

const myDict: Dictionary = {};
myDict["foo"] = "bar"; // OK
myDict["baz"] = 123;   // Error: Type 'number' is not assignable to type 'string'

This helps catch mistakes before your code runs.

You can see the exact output in the screenshot below:

dictionary typescript

Here is another example of a TypeScript dictionary with number values:

let ages: { [name: string]: number } = {
  "Alice": 25,
  "Bob": 30
};

Here, every key is a string, and every value is a number.

Check out How To Find Key By Value In TypeScript Dictionary?

3. Using the Record Utility Type

TypeScript provides a built-in utility type called Record that makes creating dictionaries even easier and more concise.

Syntax:

Record<Keys, ValueType>
  • Keys: the type of keys (usually stringnumber, or a union of string literals).
  • ValueType: the type of values.

Example:

Let me show you an example.

type PhoneBook = Record<string, string>;

const phoneBook: PhoneBook = {
  "Alice": "123-4567",
  "Bob": "987-6543"
};

Advanced Example: Specific Keys

Here is an advanced example with specific keys.

type Days = "Mon" | "Tue" | "Wed";
type Schedule = Record<Days, string>;

const mySchedule: Schedule = {
  Mon: "Math",
  Tue: "Science",
  Wed: "History"
};

If you miss a key or add an extra, TypeScript will warn you.

Read How To Filter A Dictionary In TypeScript?

4. Using Map for Dictionaries

While objects and Record are great for most cases, sometimes you need more features, like any type of key (not just strings) or maintaining the insertion order. That’s where the Map object comes in.

Example:

Here is an example.

const userRoles = new Map<number, string>();
userRoles.set(1, "Admin");
userRoles.set(2, "User");

console.log(userRoles.get(1)); // Output: "Admin"
  • Map allows any type of key (object, number, etc.).
  • Supports methods like .set().get().has().delete(), and iteration.

You can see the exact output in the screenshot below:

typescript dictionary type

Check out Convert An Array To A Dictionary In TypeScript

Iterate Over a TypeScript Dictionary

To access each key and value in a dictionary, you need to iterate over it. For object-based dictionaries, you can use a for...in loop to go through all the keys and then retrieve their values.

If you are using a Map, you can use a for...of loop, which gives you both the key and value directly as a pair. These methods make it easy to process or display every entry in your dictionary, regardless of how it’s structured.

Iterating Over Object Dictionaries

Here is an example of iterate over object dictionaries in TypeScript.

const phoneBook: Record<string, string> = {
  "Alice": "123-4567",
  "Bob": "987-6543"
};

for (const name in phoneBook) {
  if (phoneBook.hasOwnProperty(name)) {
    console.log(`${name}: ${phoneBook[name]}`);
  }
}

Iterate Over Map

Here, you can see how to iterate over map in TypeScript.

const userRoles = new Map<number, string>();
userRoles.set(1, "Admin");
userRoles.set(2, "User");

for (const [id, role] of userRoles) {
  console.log(`${id}: ${role}`);
}

Read Get First Element from a Typescript Dictionary

Optional and Readonly Keys in TypeScript

Here is how to work with optional and readonly keys in TypeScript.

Optional Keys

You can make keys optional in your TypeScript dictionary by using ?. Here is an example.

interface OptionalDict {
  [key: string]: string | undefined;
}

const dict: OptionalDict = {};
dict["foo"] = undefined;

Readonly Dictionaries

You can make a TypeScript dictionary read-only so it can’t be modified and you can see an example.

type ReadonlyDict = Readonly<Record<string, string>>;

const readOnly: ReadonlyDict = { "key": "value" };
// readOnly["key"] = "new"; // Error: Cannot assign to 'key'

Check out Check If Value Exists In Dictionary In TypeScript

Merge and Update a TypeScript Dictionary

Let us see how to merge and update a TypeScript dictionary with an example.

Merge

You can merge two TypeScript dictionaries using the spread operator:

const a = { "foo": "bar" };
const b = { "baz": "qux" };
const merged = { ...a, ...b }; // { "foo": "bar", "baz": "qux" }

Update

Here is an example of updated TypeScript dictionaries. Just assign a new value to a key:

merged["foo"] = "updated";

Conclusion

A dictionary in TypeScript is a powerful way to store and access data by key. By using interfaces, index signatures, Record, and Map, you can build type-safe, maintainable code that is easy to read and debug. Start with basic object dictionaries, move to Record for convenience, and use Map for advanced needs.

You may also like the following tutorials:

Leave a Comment

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App