Skip to content
IT glossary
ProgrammingUpdated December 3, 2026

Generics

Дженерики

Generics let one function or data structure work with several types without losing track of which type it uses. For example, the same list implementation can hold strings or numbers while the type checker keeps the two uses straight.

Also known as: обобщённые типы

What generics do

A list of names and a list of scores need the same operations: add an item, read an item, and so on. What changes is the type of the item. Instead of writing a separate list for every type, you can define a generic list and let callers specify the element type. A name read from a list of strings is still known to be a string. This is a form of parametric polymorphism: the same implementation works with different type arguments.

Type parameters and inference

In a declaration such as Box<T>, T is a type parameter. In Box<string>, string is the type argument supplied for it. Generic functions often don't need explicit type arguments because the compiler can infer them from the values passed in. Reusing a type parameter in a signature expresses a relationship: if a function takes a value of type T and returns T, the caller gets a result of the same inferred or specified type.

A TypeScript example

function wrap<T>(value: T): { value: T } {
  return { value };
}

const score = wrap(42);
score.value.toFixed(2);    // OK
score.value.toUpperCase(); // Type error

TypeScript infers a numeric type from the argument, so the result's value supports number methods but not string methods. If the parameter and the result property were both typed as any, the checker would allow both calls, even though the second one would fail at runtime.

Constraints and common mistakes

With an unconstrained T, the function can't assume that values have a particular property. If it needs to read an id, a constraint like T extends { id: string } guarantees that property while still letting the caller supply a more specific type. That's useful when a function also returns T: returning only { id: string } would hide the other properties from the caller's type checker.

Generics are common in collections, functions that transform data, and async APIs. But don't add a type parameter just because a function accepts several kinds of values. If it only needs to read an id and returns a string, an ordinary parameter type of { id: string } may be enough.

What comes up in interviews

Expect to explain what a call infers, why a constraint is necessary, or whether the type argument is available at runtime. That last answer depends on the language. TypeScript erases type parameters when it emits JavaScript, so a generic annotation won't validate an API response. In C#, reflection can inspect the type arguments of a constructed generic type.