TypeScript Generics
A generic is a type that works with any type you give it, written as <T>. It keeps a function or container reusable without losing type safety.
function first<T>(items: T[]): T {
return items[0]
}
const n = first([1, 2, 3]) // number
const s = first(["a", "b"]) // string
Try it yourself
Loading editor…
Generics are an advanced feature — you can write a lot of TypeScript without them, then reach for them when you need the same code to work across types.