Index Type
In TypeScript, indexed access types allow you to retrieve the type of a specific property within another type. This feature enables dynamic referencing of a property's type within an object type.
Example:
type Person = {
name: string;
age: number;
alive: boolean;
};
type NameType = Person['name']; // NameType is of type string
In this example, the Person type has properties name, age, and alive. By using Person['name'], we extract the type of the name property, which is string, and assign it to NameType.
Applications of Indexed Access Types:
1. Using Union Types: You can extract the types of multiple properties simultaneously.
type NameOrAge = Person['name' | 'age']; // NameOrAge is of type string | number
2. Combining with the keyof Operator: Retrieve the types of all properties in an object.
type PersonValues = Person[keyof Person]; // PersonValues is of type string | number | boolean
3. Extracting Array Element Types: This technique is also useful for obtaining the type of elements within an array.
const people = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
];
type PersonType = typeof people[number]; // PersonType is { name: string; age: number }
By leveraging indexed access types, you can dynamically extract and reuse the types of specific properties within objects or arrays, enhancing the flexibility and reusability of your type definitions.