Type System

TS Indexed Types

Using Indexed Types

TypeScript indexed types access object properties with dynamic keys.

What Are Indexed Types?

In TypeScript, indexed types allow developers to dynamically access the properties of an object using keys. This feature is particularly useful when dealing with objects whose keys are not known at compile time, offering a flexible approach to type-checking and ensuring code safety.

Syntax and Basic Usage

The syntax for an indexed type uses square brackets [] to specify the type of the keys that will be used to access the properties of the object. The general form is:

type ObjectType = { [key: KeyType]: ValueType };

In the example above, StringNumberDictionary is a type where each property key is a string, and each associated value is a number. This allows you to dynamically access any number of properties with string keys.

Accessing Properties Dynamically

Using indexed types, you can access object properties in a dynamic fashion. Here's how you can implement this in TypeScript:

In this setup, the getValue function takes a string key as an argument and returns the corresponding value from the dictionary if it exists, or undefined if it does not.

Benefits of Using Indexed Types

Indexed types provide several benefits:

  • Flexibility: They allow for dynamic property access, which is useful in scenarios where property keys are not predetermined.
  • Type Safety: TypeScript ensures that the values accessed conform to the specified value type, reducing runtime errors.
  • Code Readability: By clearly defining the expected types, code becomes more understandable and maintainable.

Common Use Cases

Indexed types are commonly used in applications dealing with configuration settings, dictionaries, or any structure where property keys may vary or be generated at runtime.