Skip to content
BENIBIX Learn

Generics

Also known as Generic Type, Generic Function, Type Parameter

Code written once that works with many types. A stand-in like T fills in.

Think of it like

Think of it like a lunch box that fits any food. Whatever you pack is what you get back.

Example

Lucy writes first<T> to get the first item of a list. Given numbers it gives back a number; given names it gives back a string.

Why it matters

Without generics you write the same list code for each type, or give up type checks. Generics avoid both.

Definition

Generics let you write one function or class for many types. The types are still checked. You write a stand-in type, often called T, in place of a real one. When the code is used, T becomes the real type, like number or string. A function that returns the first item of a list can then work on any list. It also knows exactly what kind of item it hands back.

Example code

typescript
function first<T>(items: T[]): T {
  return items[0];
}

const n: number = first([1, 2, 3]); // 1
T becomes number here, because the list holds numbers.

Common mistake

Adding a type stand-in that is used only once. If T appears in one place, a plain type is simpler.

Key takeaways

  1. 1
    One code, many types. Written once.
  2. 2
    A stand-in type. Often called T.
  3. 3
    Still checked. T becomes the real type.

Compare