Skip to content
Velloreth
Programming 8 min read

Generics Explained: Writing Code That Works for Any Type

Generics let you write one function or class that works with many types while keeping type safety. Learn the syntax, constraints, and common patterns.

By

The problem generics solve

Suppose you need a function that returns the first element of an array. Without generics, you have two bad options.

Option one: duplicate per type.

function firstNumber(arr) { return arr[0]; }
function firstString(arr) { return arr[0]; }
function firstUser(arr) { return arr[0]; }

This does not scale. Every new type needs a new function.

Option two: use a universal type.

function first(arr) { return arr[0]; } // returns any

This works, but the caller loses all type information. In a statically typed language you would need a cast at every call site, and a wrong cast is a runtime error the compiler cannot catch.

Generics give you a third option.

function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

const n = first([1, 2, 3]);        // number | undefined
const s = first(['a', 'b']);       // string | undefined
const u = first([{ id: 1 }]);      // { id: number } | undefined

One implementation. The compiler infers T from the argument and returns the correct type. No duplication, no casting, no loss of safety.

Type parameters

The T in first<T> is a type parameter — a placeholder for a type, filled in at the call site.

By convention:

NameMeaning
TType (the default)
U, VAdditional types
KKey
VValue
EElement
RReturn type

The names are arbitrary. T is conventional, not required.

You can have several:

function pair<T, U>(a: T, b: U): [T, U] {
  return [a, b];
}

pair('id', 42); // [string, number]

Generic constraints

Without constraints, a type parameter could be anything, so you can only use operations valid for every type. You cannot call .length on T because T might be a number.

Constraints narrow the set of allowed types:

function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

longest('hello', 'hi');        // works — strings have length
longest([1, 2, 3], [1]);       // works — arrays have length
longest(1, 2);                 // compile error — numbers do not

The constraint says: T can be anything, as long as it has a length property. Now .length is safe to use.

In Java, constraints use extends:

public static <T extends Comparable<T>> T max(List<T> items) {
    T best = items.get(0);
    for (T item : items) {
        if (item.compareTo(best) > 0) best = item;
    }
    return best;
}

The constraint T extends Comparable<T> means the type must be comparable, so compareTo is available.

Generic classes

Generics apply to classes as well as functions.

class Stack<T> {
  private items: T[] = [];

  push(item: T): void {
    this.items.push(item);
  }

  pop(): T | undefined {
    return this.items.pop();
  }

  get size(): number {
    return this.items.length;
  }
}

const numbers = new Stack<number>();
numbers.push(1);
numbers.push('two'); // compile error — not a number

This is how every collection library works. Array<T>, Map<K, V>, List<T>, HashMap<K, V>, Vec<T> — all generic.

Generic interfaces

interface Repository<T> {
  findById(id: string): Promise<T | null>;
  save(entity: T): Promise<void>;
  delete(id: string): Promise<void>;
}

class UserRepository implements Repository<User> {
  async findById(id: string) { /* ... */ }
  async save(user: User) { /* ... */ }
  async delete(id: string) { /* ... */ }
}

The interface describes the shape once; each implementation fills in the type. This is the basis of the repository pattern, and it is why you can write generic data-access code.

Common patterns

The identity function

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

Trivial, but it demonstrates the key property: the return type is tied to the argument type.

Mapping

function mapArray<T, U>(items: T[], fn: (item: T) => U): U[] {
  return items.map(fn);
}

mapArray([1, 2, 3], (n) => n.toString()); // string[]

The relationship between input and output types is expressed in the signature.

Result types

type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

function parse<T>(text: string): Result<T> {
  try {
    return { ok: true, value: JSON.parse(text) as T };
  } catch (error) {
    return { ok: false, error: error as Error };
  }
}

The success value and the error type are both parameters, so callers get precise types.

Key-value access

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const user = { name: 'Ada', age: 36 };
getProperty(user, 'name'); // string
getProperty(user, 'age');  // number
getProperty(user, 'email'); // compile error — not a key

This is one of the most useful patterns in TypeScript. The return type is derived from the key, so the compiler knows exactly what you get back.

Type erasure

In Java and TypeScript, generic type information is erased at compile time. It exists for the compiler and disappears from the running program.

function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

Compiles to roughly:

function first(arr) {
  return arr[0];
}

The <T> is gone. This has consequences:

You cannot check a type parameter at runtime.

function isString<T>(value: T): boolean {
  return typeof value === 'string'; // works — checks the value
}

function isType<T>(value: unknown): boolean {
  return value instanceof T; // compile error — T does not exist at runtime
}

You cannot create an array of a generic type directly.

function makeArray<T>(size: number): T[] {
  return new Array<T>(size); // works in TS, but the elements are undefined
}

Overloads that differ only by type parameter collide.

void process(List<String> items) { }
void process(List<Integer> items) { } // compile error: same erasure

Java works around this with bounded wildcards and explicit Class<T> parameters. TypeScript works around it with runtime type guards.

C# and C++ do not erase generics. C# reifies them, so typeof(T) works. C++ templates are instantiated per type at compile time, producing separate machine code for each.

When not to use generics

When a concrete type is clearer. If a function only ever handles users, take a User, not a T.

When a union is clearer. string | number is more readable than a constrained T when there are only two cases.

When the type parameter appears once. If T appears only in the parameter list and not in the return type, it is probably not adding value:

function log<T>(value: T): void { console.log(value); } // T is pointless
function log(value: unknown): void { console.log(value); } // clearer

When it makes the signature unreadable. Deeply nested generics with multiple constraints are hard to read and hard to debug. Sometimes a concrete type or an overload is better.

Generics versus other approaches

It is worth comparing generics against the alternatives, because the right choice depends on what you are trying to express.

Generics versus a union type. A union like string | number is concrete and readable when there are a small, fixed number of cases. Generics are better when the set of types is open and the relationship between input and output matters. If you find yourself writing string | number | boolean | Date, a generic is probably clearer.

Generics versus any or Object. Using a universal type is the pre-generics approach. It works, but it discards type information, so callers must cast, and a wrong cast is a runtime error the compiler cannot catch. Generics preserve the information through the whole call chain.

Generics versus code generation. Some languages solve the duplication problem by generating specialised code per type. C++ templates are closer to this than to Java generics, because each instantiation produces separate machine code. That gives better performance and allows operations that erasure forbids, at the cost of larger binaries and slower compiles.

Generics versus overloads. If a function has three concrete variants, three overloads may be clearer than one generic with constraints. Overloads are explicit and produce precise error messages; generics are concise and scale to any number of types. Reach for overloads when the set is small and fixed, and generics when it is open.

The judgement is the same as with any abstraction: use the least powerful tool that expresses the intent. A concrete type beats a union, a union beats a generic, and a generic beats any.

Practical guidance

  • Use generics for containers, transformations, and result types — anywhere the input-output type relationship matters.
  • Constrain type parameters to the minimum you need.
  • Name type parameters meaningfully when T is ambiguous — TKey, TValue, TResult.
  • Remember erasure in Java and TypeScript, and use runtime guards where you need runtime checks.
  • Prefer inference — callers should rarely need to write the type argument explicitly.
  • Do not over-generalise. If a concrete type works, use it.

For the underlying concepts, see type systems explained and static vs dynamic typing. For how generics shape design, interfaces vs abstract classes and dependency injection without a framework.

Quotable summary

Generics let you write one implementation that works with many types while the compiler checks each use, replacing both code duplication and unsafe casts to a universal type. A type parameter is a placeholder filled in at the call site, which is why the same function returns the correct type for each input. Constraints restrict what a type parameter can be, allowing you to call methods on it while keeping flexibility. Type erasure in Java and TypeScript removes generic information at runtime, so you cannot check a type parameter with instanceof or create a truly typed array. Generics are the foundation of every collection library, and they are most valuable where the relationship between input and output types matters.

Frequently asked questions

What are generics in simple terms?
Generics let you write a function or class with a placeholder for the type, so the same code works for numbers, strings, or your own objects. The compiler fills in the placeholder at each use and checks that it is consistent.
Why do generics exist?
Because the alternative is either duplicating code for every type or using a universal type like Object or any, which loses type safety and requires casting. Generics give you one implementation with full type checking.
What is a type parameter?
A type parameter is the placeholder in a generic declaration, conventionally written T, U, or K and V. It is replaced with a concrete type when the generic is used, such as Array<string>.
What are generic constraints?
Constraints limit which types a type parameter can accept, so you can rely on certain members existing. In TypeScript, extends limits it; in Java, extends or super does. Without constraints, you can only use operations valid for every type.
What is type erasure?
Type erasure means generic type information is removed at compile time, so it is not available at runtime. Java and TypeScript both erase generics, which is why you cannot check instanceof against a type parameter or create an array of a generic type.
When should I use generics?
Use them when the same logic applies to many types and the relationship between input and output types matters, such as a container, a mapping function, or a result type. Do not use them when a concrete type or a union would be clearer.