TypeScript Course
TypeScript
/
Intermediate

Index Signatures

Definition

A way to type an object when you don't know the exact names of the object's properties ahead of time, but you do know the shape of the values.

Explain Like I'm New

Imagine an English dictionary. You don't know exactly what words are going to be in the book, but you know that every single word (the Key) will be a String, and every definition (the Value) will also be a String. An Index Signature is how you tell TypeScript this rule.

Real World Example

Typing a translation JSON file where the keys are dynamic language codes ('en', 'es', 'fr') and the values are the translation strings.

Common Use Cases

  • •Dictionaries / Hash Maps
  • •Dynamic CSS modules
  • •Environment variables

Interactive Example

// We don't know the keys, but we know all values are numbers
interface SalaryDictionary {
  [employeeName: string]: number;
}

const salaries: SalaryDictionary = {
  alice: 100000,
  bob: 95000,
  charlie: 105000
};

// ERROR: Type 'string' is not assignable to type 'number'.
// salaries.dave = "High";

// Mixing known properties (They must match the index type)
interface FlexibleDict {
  id: string;
  [key: string]: string; // Because of this, 'id' MUST be a string
}

Interview Questions

basic

  • What is the syntax for an Index Signature?

intermediate

  • Can you mix known properties with an index signature?

advanced

  • Can the key of an index signature be a boolean?

Flash Cards

Question

Can you mix known properties?

Click to reveal answer
Answer

Yes, but with a strict rule: The known properties MUST be of the same type as the index signature's value. If your signature is `[key: string]: number`, you cannot have a known property `name: string`.

Question

Can the key be a boolean?

Click to reveal answer
Answer

No. The key type in an index signature MUST be `string`, `number`, `symbol`, or a template literal type. Booleans are not valid object keys in JavaScript.