Generics

Write a function or type once so it works with any type, while keeping that type checked.

What is it?

Here's a function that returns whatever you give it:

function identity(value: number): number { return value; }

It works for numbers but not strings. You'd need a near-copy for every type, or you'd use any, which drops all checking (a caller could pass a number and treat the result as a string with no error).

What you want is "whatever type goes in, the same type comes out." You express that with a type variable, usually named T, in angle brackets before the parameters:

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

Now identity(5) returns a number and identity("hi") returns a string. TypeScript works out T for each call from what you passed. Code written once that works for many types, with each use fully checked, is called a generic.

Explain like I'm 10

A generic function is like an adjustable box mold. Put in a small ball, get a small box; put in a big book, get a big box. One mold, but it never mixes up sizes: the box always fits what went in.

Examples

A generic identity function

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

const num = identity(5);        // T is inferred as number
const str = identity("hello");  // T is inferred as string

const wrong: string = identity(5);
// Error: Type 'number' is not assignable to type 'string'.

T stands for "whatever type is passed in." TypeScript works out T for each call and uses it to check both the argument and how the result is used.

A generic function over arrays

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

const firstNum = firstItem([1, 2, 3]);         // number | undefined
const firstName = firstItem(["Ana", "Bo"]);    // string | undefined

// Generics can also be constrained:
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

longest("hi", "hello"); // works — strings have .length
longest(3, 4);
// Error: number doesn't satisfy the constraint '{ length: number }'.

firstItem works for an array of any type. The extends clause on longest limits T to types with a .length property, so plain numbers are rejected.

How it works

When you call a generic function, the compiler looks at the arguments and works out what T must be. This is type inference. It then puts that type everywhere T appears and checks the call as if you'd written the type by hand.

You can also set T yourself, like identity<string>("hi"), to be precise or when inference can't work it out. A constraint (T extends SomeShape) limits what T can be, so the function body can rely on T having certain properties.

Why does it exist?

Without generics you must either duplicate logic for every type (numberIdentity, stringIdentity and so on) or use any and lose checking. Generics let you write the logic once and still get specific type checking on every call.

When to use it

Use generics when the logic doesn't depend on a specific type: functions that store, return, wrap or transform what they're given (arrays, containers, caches, API wrappers). They also suit reusable interfaces, like an ApiResponse<T> that wraps different kinds of data.

When not to use it

If a function only ever works with one type, a type variable is needless complexity. Write the concrete type. Generics are for type-independent logic, not something to add to every function.

Common mistakes

  • Adding <T> to a function that never uses T in its parameters or return type. If T isn't tied to anything, it checks nothing.

  • Using any when you mean "any type, but the same type throughout." A generic captures that; any doesn't.

  • Skipping a constraint (extends) and then using a property in the body that not every T has.

Practice exercises

  1. Easy:

    Write a generic function wrapInArray<T>(value: T): T[] that returns a one-element array containing the value.

  2. Medium:

    Write a generic function pluck<T>(items: T[], index: number): T | undefined that safely returns the item at an index.

  3. Hard:

    Write a generic function merge<T extends object, U extends object>(a: T, b: U): T & U that merges two objects and returns their intersection type.

Interview questions

What problem do generics solve that writing a separate function per type would also solve, but worse?

You write the logic once and still get type-specific checking on every call, instead of near-identical copies like numberIdentity and stringIdentity.

Why is `any` a worse alternative to a generic for a function like `identity`?

any turns off checking, so a caller could pass a number and treat the result as a string with no error. A generic ties the return type to the type passed in.

Given `function identity<T>(value: T): T { return value; }`, what type is inferred for `identity(5)`, and how does TypeScript arrive at it?

number. TypeScript works out T from the argument 5, then uses number everywhere T appears in the signature.

Why does `const wrong: string = identity(5);` fail to compile?

T is inferred as number, so identity(5) returns a number, which can't be assigned to a string variable.

How does TypeScript infer a generic type variable when you call the function without specifying it explicitly?

From the arguments at the call site. It picks the most specific type that makes the call valid and uses it as T for that call only.

How do you explicitly specify a generic type argument instead of relying on inference, and when might you need to?

In angle brackets at the call site, like identity<string>("hi"). Use it when inference can't find a specific enough type, or for clarity.

What does adding a constraint like `T extends { length: number }` do to a generic type parameter?

It limits T to types that have a .length property. The body can then safely use .length, and any type with it is still accepted.

Why does `longest(3, 4)` fail to compile when `longest` is declared as `function longest<T extends { length: number }>(a: T, b: T): T`?

number has no .length property, so it doesn't satisfy the constraint.

What's wrong with a generic function whose type parameter `T` never actually appears in its parameters or return type?

With no input or output tied to T, there's nothing to infer it from and nothing to check. It's generic in name only.

Given `function firstItem<T>(items: T[]): T | undefined`, what's the inferred type of `firstItem(["Ana", "Bo"])`?

string | undefined. T is inferred as string, and the declared | undefined covers an empty array.

Why does `firstItem`'s return type include `| undefined` even though the function body doesn't check the array's length before indexing?

By default, array indexing doesn't add undefined for out-of-bounds access. The | undefined is written by hand to honestly represent the empty-array case; the compiler wouldn't infer it.

What's the difference between constraining a generic with `T extends SomeShape` and simply typing a parameter as a union?

A constraint limits which types T may be but keeps and returns the caller's exact type. A union parameter accepts a fixed set of types, and any related return value is only known as that wide union.

Can generics be used on interfaces and type aliases, not just functions?

Yes. interface ApiResponse<T> { data: T; error?: string } describes a wrapper whose contents vary by use while its own shape stays the same.

Why doesn't `any` capture the idea of "any type, but the same type consistently throughout one call" the way a generic does?

any turns off checking for each use separately, so nothing keeps the input and output the same type. A generic ties every T in a call to one inferred type.

What could go wrong with `function merge<T, U>(a: T, b: U): T & U` if it's called with two primitives, like `merge(1, "a")`?

Without constraints T and U can be anything. number & string is never, so the return type is unusable for that call even though it compiles.

How does adding `T extends object, U extends object` to `merge` prevent that problem?

It rules out primitives, so T & U is always an intersection of two object shapes that can be merged sensibly.

When would you prefer a generic function over writing several function overloads, one per accepted type?

When the logic is the same for every type. Generics express that with one implementation; overloads suit different behavior or return types per input type.

Why is the minimal `identity<T>(value: T): T` function a useful example for understanding generics, despite doing so little?

It shows the core mechanism alone: a type variable flowing from parameter to return type, inferred per call and preserved through the signature.

What happens if you call `identity<string>(5)`, explicitly specifying `T` as `string`?

A compile error. Setting T doesn't change the argument's type; it fixes what T must be, and 5 (a number) isn't assignable to string.

Does specifying a generic type argument explicitly skip the compiler's checking of the argument against it?

No. It fixes T for that call, but each argument is still checked against the resulting parameter types.

Why might inference occasionally fail to pin down a specific-enough type, forcing you to specify `T` explicitly?

Some calls are ambiguous. An empty array literal, for example, gives no element to infer from, so the compiler may fall back to an overly wide type.

Does `T extends { length: number }` require the argument to be declared as implementing some specific interface, or just to structurally have a `.length` property?

Just structurally. Any type with a compatible .length: number property satisfies it, whatever its name or origin.

What does a generic type parameter default, like `interface Box<T = string>`, do?

It gives T a fallback when no type argument is supplied: plain Box acts like Box<string>. You can still write Box<number> or any other type.

Compare `function f<T extends string | number>(x: T): T` with `function f(x: string | number): string | number` — what's the key behavioral difference?

The generic version returns the caller's exact type (pass a string, get a string). The union version always returns string | number, losing that detail.

Why does using a generic parameter preserve a value's specific type through a function call, where widening to a union or `any` would lose it?

A generic ties the return type to the T inferred for that call, so the exact type carries through. A union or any return type is the same for every call, discarding the specific type.

How would you write a generic function that reverses an array while keeping full type safety?

function reverse<T>(items: T[]): T[]. A number[] gives back number[] and a string[] gives back string[].

Why is a generic container type, like a `Box<T>` that stores and later returns a value, preferable to using `any` for the stored value?

With any, you can store one type and read it back as another. Box<T> remembers the type it was created with and enforces it on every read.

What's the relationship between a generic function's type parameter and the concept of type inference specifically?

Inference is how TypeScript decides what the type parameter is for each call, from the arguments. Without it, you'd have to write the type argument by hand on every call.