What are Generics (<>) in TypeScript?

The angle brackets (<>) in Promise<User> are called generics. Generics let you tell TypeScript what type of data a function, class, or object will work with. You’ll see this pattern in many places, not just with promises.

  • Promise<User> means “a promise that will resolve to a User.”
  • Array<string> means “an array of strings.”
  • You’ll also see generics in other libraries, like Response<Product[]> in Express, which means “a response that will contain an array of Product objects.”

Generics make your code more flexible and type-safe, because you can specify exactly what type of data you expect.



Tags: