Course contentsShow
← TypeScript
Lesson 1029 of 1,79624. Classes in TypeScriptFree lesson

Index Signatures in Classes

Use index signatures to allow dynamic property access with type safety.

Index Signatures in Classes

You'll learn how to use index signatures in classes to allow dynamic property access while maintaining type safety.

What Are Index Signatures in Classes?

Sometimes you need a class that can accept properties you don't know about at compile time—like a dynamic configuration object or a flexible data store. Index signatures in classes let you define what types those unknown properties can have, giving you the flexibility of dynamic properties with the safety of TypeScript's type system.

Think of it like a filing cabinet with labeled drawers. You might not know every label ahead of time, but you can specify that "whatever the label says, the contents must be folders" (or strings, or numbers, or whatever type you choose).

Basic Syntax

class DynamicStore {
  [key: string]: string;
  
  // You can still have known properties
  // as long as their types match the index signature
  name: string = "Store";
}

const store = new DynamicStore();
store.name; // OK: "Store"
store.anything = "value"; // OK: string
store.somethingElse = "another"; // OK: string

The index signature [key: string]: string means "any string key will have a string value."

Important Constraints

All explicitly declared properties must be compatible with the index signature type:

class Config {
  [key: string]: string | number;
  
  name: string = "Config"; // OK: string matches
  port: number = 3000; // OK: number matches
  
  // This would error:
  // active: boolean = true; // Error! boolean doesn't match string | number
}

This ensures type consistency—if TypeScript allows config[anyKey], it must be able to guarantee the result type.

When to Use This

Index signatures in classes work well for dictionaries, caches, or data structures where keys are determined at runtime:

class Cache {
  [userId: string]: string;
  
  get(id: string): string | undefined {
    return this[id];
  }
  
  set(id: string, value: string): void {
    this[id] = value;
  }
}

Key Takeaway: Index signatures in classes allow dynamic property access with type constraints, letting you combine flexibility with compile-time safety—but all known properties must comply with the signature's type.