Indexed Access Types [TypeScript]

The syntax id: User<TechDepartment>['id']; is called “Indexed Access Types” in TypeScript.

In this syntax, User<TechDepartment> is a generic type instantiation where User is a generic type that takes a parameter TechDepartment. The angle brackets < > are used to specify the generic type parameter.

The part after the colon : is an example of an indexed access type. It is used to access a specific property type of the generic type User<TechDepartment>. In this case, ['id'] is used to access the type of the id property of the User<TechDepartment> type.

To understand this better, let’s break it down step by step:

  1. User<TechDepartment>: This is a generic type instantiation where User is a generic type and TechDepartment is the type parameter passed to it.
  2. ['id']: This is the indexed access type. It is used to access the type of the id property of the User<TechDepartment> type.

For example, let’s say you have the following type definitions:

type TechDepartment = {
  id: number;
  name: string;
};
type User<T> = {
  id: number;
  department: T;
};

Now, if you use id: User<TechDepartment>['id'], it would resolve to number because the id property of the User<TechDepartment> type is of type number.

Using indexed access types is a powerful feature in TypeScript that allows you to work with generic types and access specific properties or subtypes based on the generic parameters used. It is commonly used in various TypeScript libraries and utilities to manipulate and infer types dynamically based on generic type parameters.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *