Lookup types

Lookup types are another advanced type system feature that allow us to combine the keyof operator with generic and object literals to create advanced type annotations. Let's look at an example:

function filterByProperty<T, K extends keyof T>(    property: K, entities: T[], value: T[K]) {    return entities.filter(e => e[property] === value);}

The preceding function takes two generic type arguments:

  • T is the type of the items in the array passed as the first argument of the function.
  • K is the name of the properties of T. This requirement is enforced by a generic constraint (extends keyof T).

The function also expects two arguments:

  • An array of entities of type T.
  • A value of type T[K]. The type T[K] represents the type of the value ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.