TypeScript Index Signatures Tutorial

In this TypeScript tutorial we learn how to type objects with an unknown structure, but where we know the types of the keys and values.

Index Signatures

Index Signatures allow us to type objects with an unknown structure, but where we know the types of the keys and values.

Let’s say we have a ticketing application that allows users to book seats at a cinema.

The seats are numbered A1 through 10, and goes further up the alphabet to G, also 1 through 10. The tickets themselves are numbered with some sort of unique number.

So we know that the seat numbers should be strings, and the tickets should be numbers.

We don’t want to define individual properties like A1, or E5. That’s not only repetitive, but what if we add other cinemas later on that uses a different numbering system.

Example:
class SeatAssign {
  // B1: number
}

This is where we can use index signatures to create properties dynamically.

For the dynamic property, we specify a name and type in [] (square brackets). Then we add the value’s type outside the brackets.

Syntax:
class ClassName {
  [index: type]: valueType
}

To demonstrate, let’s add an index signature to our example. We’ll give our dynamic property a name, like seat, and a type of string in this case.

In our case the tickets use numbers as their unique identifiers, so we’ll go outside the square brackets and set the type to number.

Example:
class SeatAssign {
  // B1: string
  [seat: string]: number
}

Now that we have the signature, we can create an instance and add a couple of seats.

Example:
class SeatAssign {
  // B1: string
  [seat: string]: number
}

let seats = new SeatAssign()
seats.B1 = 2718203
seats.D7 = 9835671

Summary: Points to remember

  • Index signatures allow us to create dynamic properties with type safety.
  • The dynamic property and its type is specified between square brackets, and the property’s value type is specified outside the brackets.