AI Hints
TypeScript · Lesson 52 of 120

Why Generics

Reusable types.

⏱ 2 min read▶ Video at 41:03🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Imagine a function that returns the first item of a list. For strings, it returns a string. For bikes, a bike. Writing one version per type is silly. Using any loses the type. Generics solve this.

Why Generics
From the video: Why Generics
  • One function
  • Many types
  • Keep the type

any loses the type

First item returns any. So the result has no type at all, and TypeScript can't help us. Run it. It works, but upper case on a number would only fail while running.

app.tstypescript
function firstItem(list: any[]): any {
  return list[0];
}

const store = firstItem(["Leeds", "York"]);
const price = firstItem([849.5, 450]);
console.log(store, price);
Output
Leeds 849.5

The idea

A generic function has a type parameter, a placeholder for a type, written in angle brackets. Each call fills it in. So the output type follows the input type.

keyvalue
Type parametera placeholder
Written<T>
Each callfills it in
Resulttypes flow through

Summary

Generics let one function work with many types, without losing them. Next, writing generic functions.

Key takeaways
  • any loses types
  • <T>
  • Types flow
Next up: Generic Functions — type parameters