TYPESCRIPT

TypeScript Dictionary: Syntax, Usage, and Examples

A TypeScript dictionary lets you store and access key-value pairs with full type safety. Unlike JavaScript objects, a TypeScript dictionary setup can restrict keys and enforce specific value types, making your code easier to work with and less error-prone.

How to Use a Dictionary in TypeScript

You can define a TypeScript dictionary using an index signature. This allows you to define a dynamic object where keys follow a certain pattern (like strings), and values are of a consistent type.

Basic Syntax

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

const userRoles: Dictionary = {
  alice: 'admin',
  bob: 'editor',
  charlie: 'viewer'
};

This example creates a dictionary where every key is a string and every value is also a string.

You can also use the built-in Record utility:

const statusMessages: Record<string, number> = {
  success: 200,
  error: 500,
  notFound: 404
};

Both approaches give you a TypeScript dictionary with proper type checking.

When to Use a Dictionary TypeScript Structure

Use a dictionary in TypeScript when:

  • You have dynamic keys (like usernames or IDs).
  • You want a flexible object without a fixed structure.
  • You need fast lookup and access to associated data.
  • You’re mapping identifiers to configurations, roles, or metadata.
  • You need a quick cache or registry of values you can reference by key.

If you're building forms, APIs, or state management tools, you'll likely use dictionaries regularly.

Examples of TypeScript Dictionary in Practice

Storing User Preferences

interface Preferences {
  [key: string]: boolean;
}

const userPreferences: Preferences = {
  darkMode: true,
  showNotifications: false
};

console.log(userPreferences['darkMode']); // true

This dictionary helps store and retrieve feature toggles efficiently.

Dictionary with TypeScript Dictionary Key Assertion

Sometimes, you need to assure TypeScript that a key exists:

const settings: Record<string, string> = {
  theme: 'dark',
  layout: 'grid'
};

const key = 'theme';

if (key in settings) {
  const value = settings[key as keyof typeof settings];
  console.log(value); // dark
}

Using keyof or type assertions prevents TypeScript from raising an error when you access dictionary values dynamically.

Strongly Typed Dictionary with Enums

enum Status {
  Success = 'success',
  Error = 'error'
}

type StatusColors = {
  [key in Status]: string;
};

const colors: StatusColors = {
  success: 'green',
  error: 'red'
};

Here, the keys of the dictionary are limited to a specific enum. That’s a common use in UI theming and API status handling.

Dictionary of Objects

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

const userDirectory: Record<string, User> = {
  user1: { name: 'Ava', age: 28 },
  user2: { name: 'Liam', age: 31 }
};

console.log(userDirectory['user1'].name); // Ava

A dictionary can store more than simple types—it’s perfect for structured data too.

Learn More About Dictionaries in TypeScript

Dictionary vs. Object

In TypeScript, an object can behave like a dictionary, but you lose type safety when keys and values aren't well-defined. A dictionary forces consistency and enables autocompletion and static analysis in editors.

Optional Keys in a Dictionary

You can allow keys to be optional with the ? operator:

interface OptionalFeatures {
  darkMode?: boolean;
  betaAccess?: boolean;
}

const features: OptionalFeatures = {
  darkMode: true
};

This is helpful when some values might be undefined or loaded later.

Using Union Types in Dictionary Values

type ResponseCode = 200 | 400 | 500;

const apiResponses: Record<string, ResponseCode> = {
  home: 200,
  login: 400
};

This lets you limit dictionary values to a fixed set.

Creating a Dictionary from an Array

You can build a dictionary from an array using reduce():

const users = [
  { id: 'u1', name: 'Maya' },
  { id: 'u2', name: 'Raj' }
];

const userMap = users.reduce<Record<string, string>>((acc, user) => {
  acc[user.id] = user.name;
  return acc;
}, {});

console.log(userMap['u1']); // Maya

This is common in data transformation or lookup optimization.

Dictionary with Custom Key Types

You’re not limited to strings—TypeScript allows more specific key types if you define them properly:

type Permission = 'read' | 'write' | 'delete';

const permissions: Record<Permission, boolean> = {
  read: true,
  write: false,
  delete: false
};

This setup is perfect for permission checks or configuration flags.

Dictionary with TypeScript Dictionary Type Alias

For reusable patterns, define a type alias:

type StringMap<T> = { [key: string]: T };

const fruitQuantities: StringMap<number> = {
  apple: 5,
  banana: 3
};

You can now use StringMap<T> anywhere you need a TypeScript dictionary.

Dictionary Key Checking

Always verify a key exists before using it:

const labels: Record<string, string> = {
  save: 'Save Changes',
  cancel: 'Cancel'
};

function getLabel(key: string): string {
  if (key in labels) {
    return labels[key];
  }
  return 'Unknown';
}

TypeScript won’t stop you from looking up nonexistent keys—so guard your code.

Best Practices for Dictionaries in TypeScript

  • Use Record<K, V> for quick dictionary declarations.
  • Use interfaces when you need structure and clarity.
  • Apply keyof to safely access known keys.
  • Wrap dynamic key access in checks like if (key in obj).
  • Use as assertions only when you're sure the key exists.
  • Avoid any as a value type—use real types to keep your code safe.
  • Prefer enums or union types for known key sets to avoid typos.
  • Break dictionaries into smaller types when the structure gets complex.
Learn TypeScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn TypeScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH