# Generics

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

**Field:** Software Development  
**Category:** Programming Paradigms  
**Also known as:** Generic Type, Generic Function, Type Parameter

## Think of it like

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

## 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

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.

## 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.

## Why it matters

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

## Common mistake

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

## Three principles

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

## Related terms

- [Type System](https://learn.benibix.com/term/development/type-system)
- [Type Inference](https://learn.benibix.com/term/development/type-inference)
- [TypeScript](https://learn.benibix.com/term/development/typescript)
- [Function](https://learn.benibix.com/term/development/function)

## Told apart from

- [Generics vs Union Type](https://learn.benibix.com/compare/generics-vs-union-type): People think generics and union types both just mean any type. A union type lists a few kinds a value may be, such as a string or a number, and you must check which one you have. A generic stands for one type that the caller picks. That type is then kept exact all the way through, so a list of strings gives back a string.

---

Source: https://learn.benibix.com/term/development/generics
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-17
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
