Index types are a powerful feature in TypeScript that allow you to work with the properties of an object in a more flexible and type-safe manner. They enable you to create reusable code that can operate on various object shapes while maintaining type safety.
Index types consist of two main parts:
keyof
T[K]
The keyof
operator is used to get the union of keys from an object type. It returns a union type of all the property names of the given type.
interface Person {
name: string;
age: number;
}
type PersonKeys = keyof Person; // "name" | "age"
Indexed access types allow you to look up a specific property on another type:
type PersonName = Person["name"]; // string
type PersonAge = Person["age"]; // number
Index types are particularly useful when creating generic functions that can work with different object shapes. Here's an example:
function getProperty(obj: T, key: K): T[K] {
return obj[key];
}
const person: Person = { name: "Alice", age: 30 };
const name = getProperty(person, "name"); // Returns "Alice"
const age = getProperty(person, "age"); // Returns 30
In this example, the getProperty
function can work with any object type and return the correct type for the specified property.
undefined
.To deepen your understanding of TypeScript's type system, explore these related topics:
By mastering index types, you'll be able to write more flexible and type-safe TypeScript code, especially when working with objects and their properties.