Initialize Maps in TypeScript

I was working on a TypeScript project where I had to store and retrieve user settings based on different keys. Using plain objects was not sufficient, especially when I needed keys that weren’t just strings.

Then I used Map objects, and with this I was able to store data using different types of keys, keep the entries in the order I added them, and easily perform operations like checking if a key exists or looping through the data.

In this blog, I’ll show you six practical ways to initialize a Map in TypeScript. These methods will help you to organize data more effectively in your TypeScript projects.

What is a Map in TypeScript?

A Map is a collection of key-value pairs where each key is unique. Unlike plain JavaScript objects, Maps offer several advantages:

  • Keys can be of any type (objects, functions, primitive values)
  • Maps maintain insertion order of elements
  • They have better performance for frequent additions and removals
  • They come with built-in methods for easy manipulation

Method 1: Empty Map Initialization

The simplest way to create a Map in TypeScript is to initialize an empty Map:

// Initialize an empty Map
const userPreferences = new Map<string, boolean>();

// Add elements later
userPreferences.set('darkMode', true);
userPreferences.set('notifications', false);

console.log(userPreferences.get('darkMode')); // Outputs: true

Output:

Initialize Maps in TypeScript

In this example, I’ve used TypeScript’s generic syntax Map<string, boolean> to specify that the keys will be strings and the values will be booleans.

Check out: Check If a Key Exists in a TypeScript Object

Method 2: Initialize with Array of Entries

For situations where you already know the initial values, you can initialize a Map with an array of key-value pairs:

// Initialize Map with known values
const stateCapitals = new Map<string, string>([
  ['California', 'Sacramento'],
  ['New York', 'Albany'],
  ['Texas', 'Austin'],
  ['Florida', 'Tallahassee']
]);

console.log(stateCapitals.get('Texas')); // Outputs: Austin

Output:

Initializing Maps in TypeScript

This method is efficient when you have a predefined set of values that won’t change much over time.

Method 3: Initialize from an Existing Object

Sometimes you may want to convert an existing object to a Map:

// Convert an object to a Map
const userObject = {
  name: 'John',
  email: '[email protected]',
  age: 32
};

const userMap = new Map<string, any>(
  Object.entries(userObject)
);

console.log(userMap.get('name')); // Outputs: John

Output:

Initialize Maps with Complex Keys in TypeScript

This approach is useful when working with APIs or legacy code that returns plain objects.

Check out: Check Types in TypeScript

Method 4: Initialize with Complex Keys

One of Map’s strengths is the ability to use any type as a key, including objects:

interface User {
  id: number;
  name: string;
}

// Using objects as keys
const userScores = new Map<User, number>();

const john: User = { id: 1, name: 'John' };
const sarah: User = { id: 2, name: 'Sarah' };

userScores.set(john, 85);
userScores.set(sarah, 92);

console.log(userScores.get(john)); // Outputs: 85

Output:

TypeScript Initialize Maps

Be careful when using objects as keys, though! The objects must be the same reference, not just have the same properties.

Check out: Deep Clone an Object in TypeScript

Method 5: Type-Safe Initialization with Tuples

For more complex Maps with specific value types, you can use tuple types:

type UserData = [string, number, boolean]; // [name, age, active]

const userDatabase = new Map<number, UserData>();

userDatabase.set(101, ['John Doe', 32, true]);
userDatabase.set(102, ['Jane Smith', 28, true]);
userDatabase.set(103, ['Bob Johnson', 45, false]);

const userData = userDatabase.get(101);
if (userData) {
  const [name, age, active] = userData;
  console.log(`${name} is ${age} years old and is ${active ? 'active' : 'inactive'}`);
  // Outputs: John Doe is 32 years old and is active
}

Output:

Type safe map initialization in TypeScript

This approach ensures type safety for complex value structures.

Method 6: Cloning an Existing Map

To create a new Map based on an existing one:

// Original Map
const originalMap = new Map<string, number>([
  ['apples', 5],
  ['oranges', 10],
  ['bananas', 7]
]);

// Clone the Map
const clonedMap = new Map(originalMap);

// Modify the clone without affecting the original
clonedMap.set('pears', 3);

console.log(originalMap.has('pears')); // Outputs: false
console.log(clonedMap.has('pears')); // Outputs: true

Output:

Initialize maps with cloning in TypeScript

This is useful when you need to preserve the original data while making modifications to a copy.

Working with Generic Map Types

TypeScript allows you to create reusable Map types with generics:

// Generic Map type for API responses
type ApiResponseMap<T> = Map<string, T>;

// Usage for different response types
const userResponses = new Map<string, User>();
const productResponses = new Map<string, Product>();

// Or with the generic type
const orderResponses: ApiResponseMap<Order> = new Map();

This approach helps maintain type consistency across your application.

Check out: Exception Handling in TypeScript

Common Map Operations

Once you’ve initialized your Map, here are some common operations I use frequently:

const inventory = new Map<string, number>([
  ['laptops', 25],
  ['phones', 50],
  ['tablets', 15]
]);

// Check if a key exists
if (inventory.has('phones')) {
  console.log('Phones are in stock');
}

// Get the size
console.log(`We have ${inventory.size} product types`); // Outputs: We have 3 product types

// Iterate through the Map
inventory.forEach((quantity, product) => {
  console.log(`${product}: ${quantity} in stock`);
});

// Convert to array
const productEntries = Array.from(inventory.entries());
const productNames = Array.from(inventory.keys());
const stockQuantities = Array.from(inventory.values());

// Delete an item
inventory.delete('tablets');

// Clear the entire Map
// inventory.clear();

Output:

Initialize generic map types in TypeScript

Check out: Set Default Values in TypeScript Interfaces

I hope you found this guide helpful for initializing and working with Maps in TypeScript. This powerful data structure can significantly improve your code’s readability and performance when used appropriately.

Remember that Maps provide better performance for frequent additions and removals compared to objects, and they preserve the insertion order of elements. These features make Maps an excellent choice for many use cases in modern TypeScript applications.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.