Back

Map Access in TypeScript

Indexed access types allow us to extract the type of a specific property from an object type using square bracket syntax.

Together with `keyof`, you can build dynamic and powerful utility types that reason over the structure of objects.

Using keyof to Get Object Keys

`keyof` is used to get a union of all property names (keys) of a given object type. These keys can be used as types themselves.

type User = {
    name: string;
    age: number;
  }
  
  type Keys = keyof User; // 'name' | 'age'
  
  const key: Keys = 'name';

Accessing a Property Type via Brackets

Using the bracket notation `T[K]`, you can get the type of a specific property. This is useful when you want to isolate or combine certain values.

type User = {
    name: string;
    age: number;
  }
  
  type NameOrAge = User['name'] | User['age']; 
  // string | number

Accessing All Property Types at Once

By combining `keyof` with indexed access (`T[keyof T]`), you can extract a union of all property types from an object type.

type User = {
    name: string;
    surname: string;
    age: number;
    isManager: boolean;
  }
  
  type ValueUnion = User[keyof User]; 
  // string | number | boolean

Conclusion

Map access and key lookup types are essential when building generic utilities or enforcing constraints over object structures.

Understanding how to extract and manipulate property types makes your code more flexible, reusable, and type-safe.

Back