TypeScript · Lesson 52 of 120
Why Generics
Reusable types.
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.

- 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.
| key | value |
|---|---|
| Type parameter | a placeholder |
| Written | <T> |
| Each call | fills it in |
| Result | types 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