0
0
Typescriptprogramming~5 mins

Indexed access types in Typescript

Choose your learning style9 modes available
Introduction

Indexed access types let you get the type of a specific property from another type. This helps you reuse types easily without repeating them.

When you want to use the type of a property from an object type in another place.
When you want to make sure a variable matches the type of a specific property inside an object.
When you want to create a new type based on one or more properties of an existing type.
When you want to avoid repeating type definitions and keep your code DRY (Don't Repeat Yourself).
Syntax
Typescript
type NewType = ExistingType['propertyName'];

You use square brackets with the property name as a string inside to get the type.

You can also use union of keys like ExistingType['prop1' | 'prop2'] to get combined types.

Examples
This gets the type of the name property from Person, which is string.
Typescript
type Person = { name: string; age: number };
type NameType = Person['name'];
This gets the type of age or name, so the type is number | string.
Typescript
type Person = { name: string; age: number };
type AgeOrName = Person['age' | 'name'];
This extracts the type of the make property from the Car interface.
Typescript
interface Car {
  make: string;
  year: number;
}
type MakeType = Car['make'];
Sample Program

This program shows how to use indexed access types to get property types from the User interface. We assign values matching those types and print them.

Typescript
interface User {
  id: number;
  username: string;
  isActive: boolean;
}

// Get the type of the 'username' property
let userName: User['username'];
userName = 'alice123';

// Get the type of 'id' or 'isActive'
let userInfo: User['id' | 'isActive'];
userInfo = 42; // valid
userInfo = true; // also valid

console.log(userName);
console.log(userInfo);
OutputSuccess
Important Notes

Indexed access types help keep your types consistent and avoid mistakes.

If you use a property name that does not exist, TypeScript will show an error.

You can combine indexed access types with other TypeScript features for powerful type manipulation.

Summary

Indexed access types let you get the type of a property from another type.

Use square brackets with the property name to extract the type.

This helps reuse types and keep your code clean and safe.