TypeScript Key Value Pair [Complete Guide with Practical Examples]

Do you need to store and access data in TypeScript using keys, like state abbreviations and their full names, or zip codes and city names? You can achieve this using the TypeScript key value pair.

In this tutorial, I will explain different methods to create and use key value pairs in TypeScript with real examples.

What is a Key Value Pair in TypeScript?

A key value pair is a data structure where each key (like a state abbreviation) is associated with a value (like the full state name). In TypeScript, you can implement key value pairs using objects, Maps, or even custom types for extra type safety.

Why is this useful?

Key value pairs are everywhere—think of mapping US state codes to their names, storing user settings, or organizing products by SKU. TypeScript helps you do this efficiently and with strong type checking, so you can avoid bugs and write cleaner code.

Check out TypeScript ?? Operator

Method 1: Using Objects as Key Value Pairs

The most straightforward way to represent key value pairs in TypeScript is with plain objects.

Example: Mapping US State Abbreviations to State Names

Here is an example.

const stateNames: { [key: string]: string } = {
  NY: "New York",
  CA: "California",
  TX: "Texas",
  FL: "Florida",
  IL: "Illinois"
};

// Access a value by key
console.log(stateNames["CA"]); // Output: California

How This Works

  • The keys are strings (like “NY” or “CA”).
  • The values are also strings (the full state names).
  • You can access any value using bracket notation.

Here is the exact output in the screenshot below:

TypeScript Key Value Pair

Adding Type Safety with Interfaces

If you know the exact set of keys, you can make your object even more type-safe using an interface or a type.

type USStateAbbreviation = "NY" | "CA" | "TX" | "FL" | "IL";

const stateNamesTyped: Record<USStateAbbreviation, string> = {
  NY: "New York",
  CA: "California",
  TX: "Texas",
  FL: "Florida",
  IL: "Illinois"
};

// Now TypeScript will warn you if you miss a state or add an invalid key

Check out TypeScript Enum vs Const

Method 2: Using Map for Key Value Pairs

While objects are great, sometimes you need more flexibility, like using non-string keys or preserving insertion order. That’s where JavaScript’s Map comes in, and TypeScript supports it beautifully.

Example: Mapping Zip Codes to City Names

const zipToCity = new Map<number, string>([
  [10001, "New York"],
  [90001, "Los Angeles"],
  [60601, "Chicago"],
  [77001, "Houston"],
  [33101, "Miami"]
]);

// Access a value by key
console.log(zipToCity.get(90001)); // Output: Los Angeles

Why Use Map?

  • Keys can be any type (not just strings).
  • Keeps the order of insertion.
  • Has useful methods like .set().get().has(), and .delete().

Iterating Over a Map

Here is how to iterate over a map in TypeScript.

zipToCity.forEach((city, zip) => {
  console.log(`${zip}: ${city}`);
});

Check out TypeScript Switch with Enums

Method 3: Strongly-Typed Key Value Pairs with Generics

If you want reusable, type-safe key value pairs, you can define a generic interface or type.

Example: User Preferences

interface KeyValuePair<K, V> {
  key: K;
  value: V;
}

const userPreference: KeyValuePair<string, boolean> = {
  key: "darkMode",
  value: true
};

Using Arrays of Key Value Pairs

Sometimes, you may want to work with an array of key value pairs—like user settings or configuration options.

const userSettings: KeyValuePair<string, string>[] = [
  { key: "theme", value: "light" },
  { key: "timezone", value: "America/New_York" },
  { key: "language", value: "en-US" }
];

// Find a setting by key
const timezone = userSettings.find(setting => setting.key === "timezone")?.value;
console.log(timezone); // Output: America/New_York

Read TypeScript keyof with Strings

Method 4: Using Enums as Keys

Enums are great when you want to restrict keys to a predefined set of values.

Example: Mapping Payment Methods

enum PaymentMethod {
  CreditCard = "CreditCard",
  PayPal = "PayPal",
  ACH = "ACH"
}

const paymentDescriptions: Record<PaymentMethod, string> = {
  [PaymentMethod.CreditCard]: "Pay with credit card",
  [PaymentMethod.PayPal]: "Pay via PayPal",
  [PaymentMethod.ACH]: "Pay via bank transfer"
};

Check out Check If a Value Is in an Enum in TypeScript

Method 5: Using Index Signatures for Flexible Key Value Stores

If you need a flexible object where keys are not known in advance, you can use an index signature.

Example: Storing API Response Data

interface ApiResponse {
  [key: string]: any;
}

const response: ApiResponse = {
  userId: 12345,
  userName: "john_doe",
  isActive: true,
  lastLogin: "2024-06-12T08:00:00Z"
};

In this tutorial, I explain various methods for working with TypeScript key value pairs, providing examples. If you have any questions or want to share how you use key value pairs in your TypeScript projects, feel free to leave a comment below.

You may also like the following tutorials:

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