Indexed Access Types are a powerful feature in TypeScript that allow you to access and manipulate types using their property names. This concept is crucial for creating flexible and type-safe code when working with complex object structures.
In TypeScript, Indexed Access Types provide a way to look up a specific property on another type. They're particularly useful when you need to work with dynamic property names or when you want to extract the type of a specific property from an object type.
The syntax for Indexed Access Types is straightforward:
type PropertyType = ObjectType[KeyType];
Here, ObjectType
is the type you're accessing, and KeyType
is the property name you want to look up.
interface Person {
name: string;
age: number;
}
type AgeType = Person['age']; // number
In this example, AgeType
is inferred as number
because that's the type of the age
property in the Person
interface.
type PersonProps = 'name' | 'age';
type PersonPropsType = Person[PersonProps]; // string | number
Here, PersonPropsType
is a union of string
and number
, as those are the types of the name
and age
properties respectively.
Indexed Access Types can be combined with other TypeScript features for more complex type manipulations:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const person = { name: "Alice", age: 30 };
const name = getProperty(person, "name"); // string
const age = getProperty(person, "age"); // number
This example demonstrates how Indexed Access Types can be used with generics to create type-safe property access functions.
To deepen your understanding of TypeScript's type system, explore these related topics:
Mastering Indexed Access Types is a significant step towards writing more flexible and type-safe TypeScript code. They provide a powerful way to work with complex object structures while maintaining strong typing throughout your codebase.