Skip to content
FrontDepth, Home

TypeScript

Generics

How generics keep the relation between the types that go into a function or type and the types that come out: type parameters and inference at call sites, constraints, keyof with indexed access, defaults, generic classes, unnecessary type parameters, const type parameters, NoInfer and variance.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

This topic starts at Junior level.

JuniorConcept

Why generics

A function that works with many types still has to say what it returns. Take a helper that returns the first element of an array. With any it accepts every array, but the link between what goes in and what comes out is lost:

TypeScript
function firstAny(items: any[]): any {
  return items[0];
}

const id = firstAny(["a1", "b2"]); // id: any
id.toFixed(2); // compiles, throws a TypeError at run time

unknown instead of any is safe, but then every caller has to a value whose type it already knows. One function per type (firstString, firstNumber) does not scale either.

solve this with a type parameter: a placeholder for a type, written in angle brackets, that is filled in at each call.

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

const a = first(["a1", "b2"]); // a: string | undefined
const n = first([1, 2, 3]); // n: number | undefined

a?.toUpperCase(); // OK
n?.toUpperCase(); // Error: Property 'toUpperCase' does not exist on type 'number'.

Read the signature as a sentence: "for any type T, give me an array of T and I return a T, or undefined for an empty array". The function no longer promises one specific type; it promises a relation between the argument and the result. That relation is exactly what any throws away.

The | undefined is honest. Unless noUncheckedIndexedAccess is on, items[0] is typed as T, so the compiler would also accept : T as the return type, and the function would still return undefined for [].

Generics you already use

Many built-in types are generic. string[] is shorthand for Array<string>, fetch() returns Promise<Response>, and Map<K, V> and Set<T> take their key and value types.

What a type parameter is not

T exists only for the type checker. Like every type, it is when the code is compiled, so the body cannot ask what T is: there is no typeof T, and first<number> and first<string> run exactly the same JavaScript. A generic function has to work for every type it accepts.

Single letters are the convention for short signatures: T for a type, K for a key, V for a value. In a longer signature, a name such as TItem or Item reads better.

JuniorConcept

Type arguments and inference

You can pass the type argument yourself, or let TypeScript work it out:

TypeScript
first<string>(["a", "b"]); // explicit
first(["a", "b"]); // inferred: T is string

Working out the type argument from the call is . TypeScript matches each argument against its parameter type: ["a", "b"] is a string[], the parameter is T[], so T is string. Prefer inference, and write a type argument only when inference has nothing to work with or picks a type you did not mean.

Inference flows into callbacks

With several type parameters, inference works through the arguments:

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

const lengths = map(["a", "bb"], (s) => s.length); // number[]

T comes from the array, so the callback's s is already a string without an annotation (the callback is contextually typed), and U comes from what the callback returns.

When inference picks something else

TypeScript
function combine<T>(a: T[], b: T[]): T[] {
  return a.concat(b);
}

combine([1, 2], ["x"]); // Error: Type 'string' is not assignable to type 'number'.
combine<string | number>([1, 2], ["x"]); // OK: you said what you meant

T is inferred from the first array as number, and the second array is then checked against number[]. If mixing is intended, say so with an explicit type argument.

When there is nothing to infer from

TypeScript
const byId = new Map(); // Map<any, any>: nothing stored in it is checked
const tags = new Set(); // Set<unknown>
const users = new Map<string, User>(); // say what goes in

An empty collection gives inference no candidates, so the type falls back to any or unknown. Pass the type arguments when you create it.

Two details worth knowing

  • Explicit type arguments are all or nothing: map<string>(…) fails with "Expected 2 type arguments, but got 1." unless the missing ones have defaults.
  • Literal types are kept or widened depending on where they end up. const x = identity("hi") (with identity<T>(value: T): T) gives "hi", let x = identity("hi") gives string, and first(["a", "b"]) gives string | undefined, not "a" | "b" | undefined.
JuniorConcept

Constraints with extends

Inside a generic function T can be any type, so you can only do with a T what works for every type:

TypeScript
function longest<T>(a: T, b: T): T {
  return a.length >= b.length ? a : b; // Error: Property 'length' does not exist on type 'T'.
}

A constraint limits which types T accepts and, in return, tells the body what it can rely on:

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

longest("apple", "fig"); // OK: strings have a length
longest([1, 2], [3]); // OK: T is number[]
longest(10, 20); // Error: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.

extends here means "is assignable to", not class inheritance. Any type can be a constraint: T extends string, T extends object, T extends readonly unknown[], T extends (...args: never[]) => unknown.

Why not annotate with the constraint?

TypeScript
function longestLoose(a: { length: number }, b: { length: number }) {
  return a.length >= b.length ? a : b;
}

longestLoose("apple", "fig").toUpperCase(); // Error: Property 'toUpperCase' does not exist on type '{ length: number; }'.
longest("apple", "fig").toUpperCase(); // OK

The version without a type parameter accepts the same arguments but returns { length: number }: the caller passed strings and gets back something that is no longer a string. The constraint says what T must have; the type parameter keeps everything else it has.

The classic mistake: returning something that only fits the constraint

TypeScript
function minimumLength<T extends { length: number }>(obj: T, minimum: number): T {
  if (obj.length >= minimum) return obj;
  return { length: minimum }; // Error
}

The error reads: "'{ length: number; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{ length: number; }'." The signature promises to return the same type that came in, not just any object with a length. A caller that passes number[] would get { length: 6 } back, typed as number[], and crash on .slice(). The TypeScript handbook uses this exact example.

The fix is to return a real T or to change the return type to { length: number }. Adding as T makes the error go away and leaves the crash in place.

MiddleConcept

keyof and indexed access in generic functions

Two type operators make generics useful for objects: keyof T is the union of T's property names, and T[K], an indexed access type, is the type of property K. With a constraint that ties one type parameter to another, they give a type-safe property getter, the example the TypeScript handbook uses:

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

const user = { id: 7, name: "Aysel", email: null as string | null };

getProperty(user, "id"); // number
getProperty(user, "email"); // string | null
getProperty(user, "phone"); // Error: Argument of type '"phone"' is not assignable to parameter of type '"id" | "name" | "email"'.

K extends keyof T means "K is one of T's keys". At the call, T is inferred from user and K from the string you pass, as the literal type "id", so the return type T[K] becomes number.

Why two type parameters

TypeScript
function getLoose<T>(obj: T, key: keyof T) {
  return obj[key];
}

getLoose(user, "id"); // string | number | null

With key: keyof T, the function no longer knows which key was passed, so the result is T[keyof T]: the union of every property's type. The extra K exists to remember the specific key. The same pattern types a setter, where the value must match the key:

TypeScript
function setProperty<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
  obj[key] = value;
}

setProperty(user, "id", "7"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.

It also types helpers such as pluck(items, key) returning T[K][], sorting or grouping by a key, and form libraries where setValue("email", value) checks the value against the field.

Two things to know about keys

  • Object.keys(obj) returns string[], not (keyof T)[]. Typing is , so an object can have more properties than its type lists, and TypeScript will not promise that every key is a keyof T. Indexing obj with such a key fails under strict: "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type …". Iterate over a typed list of the keys you expect, or, where you know no extra keys can appear, assert once (as (keyof T)[]) and say why in a comment.
  • keyof of an index signature includes number. For { [key: string]: number }, keyof is string | number, because JavaScript turns numeric property keys into strings.
MiddleConcept

Generic interfaces, classes and defaults

Type parameters also go on interfaces, type aliases and classes. A generic type is a template: wherever it is used, it needs its type arguments.

TypeScript
interface ApiResponse<T> {
  data: T;
  status: number;
}

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

const response: ApiResponse<User[]> = { data: [], status: 200 };
const parsed: Result<number> = { ok: false, error: new Error("Not a number") };
let broken: ApiResponse; // Error: Generic type 'ApiResponse<T>' requires 1 type argument(s).

Default type parameters

E = Error is a default: leave it out, and Result<number> means Result<number, Error>. The rules the handbook lists, in short:

  • a type parameter with a default is optional, and required ones may not follow it: <T = string, U> fails with "Required type parameters may not follow optional type parameters.";
  • the default must satisfy the constraint: <T extends string = number> is an error;
  • when you pass type arguments, you only have to pass the required ones;
  • in a call, when inference finds no candidate, the default is used instead of unknown.

Generic classes

TypeScript
class Cache<K, V> {
  #items = new Map<K, V>();

  get(key: K): V | undefined {
    return this.#items.get(key);
  }

  set(key: K, value: V): this {
    this.#items.set(key, value);
    return this;
  }
}

const prices = new Cache<string, number>();
prices.set("apple", 1.2);
prices.set("pear", "cheap"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.

A class's type parameters belong to its instances: each new Cache<…>() fixes K and V for that object. Static members are shared by all instances, so they cannot use them: static empty: V fails with "Static members cannot reference class type parameters." With no type arguments and nothing to infer from, new Cache() is a Cache<unknown, unknown>.

On the class or on the method?

Put the type parameter on the class when every method shares it, as in a cache of prices. Put it on the method when each call stands alone:

TypeScript
class Logger {
  tap<T>(value: T): T {
    console.log(value);
    return value;
  }
}

const order = new Logger().tap({ id: 1 }); // { id: number }

A Logger<T> would force one logger per type for no reason.

MiddlePitfalls

When a generic is unnecessary

A type parameter earns its place by relating two things: an argument and the result, two arguments, a key and its value. The TypeScript handbook puts it as a rule: if a type parameter appears in only one place, strongly reconsider whether you need it. The inferred return type counts as a place.

Used once: just use the type

TypeScript
function greet<S extends string>(name: S): void {
  console.log("Hello, " + name);
}

S relates nothing, and greet(name: string) says the same thing more simply. The same goes for format<T extends string | number>(value: T): string: a union parameter type does the job.

Return type only: an unchecked cast in disguise

TypeScript
async function fetchJson<T>(url: string): Promise<T> {
  const response = await fetch(url);
  return response.json(); // any, accepted as T
}

const me = await fetchJson<User>("/api/me");

T appears only in the return type, so nothing connects it to the data. response.json() returns Promise<any>, any is assignable to every T, and the compiler accepts whatever the caller asks for. The call looks like a typed API, but it is a , as User, with extra steps: if the server answers { "error": "expired" }, me.name is undefined and no type caught it. parseJson<T>(text), storage.get<T>(key) and similar helpers have the same problem.

Return unknown and validate at the boundary instead, or take the validator as a parameter so that the type parameter relates something real:

TypeScript
async function fetchJson<T>(url: string, parse: (data: unknown) => T): Promise<T> {
  const response = await fetch(url);
  return parse(await response.json());
}

const me = await fetchJson("/api/me", parseUser); // T is User, inferred from parseUser

Now T comes from the parser, and the data is checked before anyone uses it.

Push type parameters down, use fewer of them

Two more guidelines from the handbook:

TypeScript
function firstElement1<T>(arr: T[]) {
  return arr[0]; // returns T
}

function firstElement2<T extends any[]>(arr: T) {
  return arr[0]; // returns any
}

firstElement2([1, 2, 3]) returns any, because the body indexes the constraint any[] instead of waiting for the element type. Make the type parameter the thing you care about, here the element, not the whole argument. And a type parameter such as Func extends (arg: T) => boolean, which relates nothing, only makes callers who pass type arguments write one more.

MiddleExample

Worked example: a typed event emitter

A typed event emitter combines everything so far: a constraint, keyof, indexed access, and type parameters on a class and on its methods. One type describes every event and its payload; on and emit reject wrong names and wrong payloads.

TypeScript
type AppEvents = {
  login: { userId: string };
  logout: undefined;
  "cart:add": { productId: string; quantity: number };
};

type Handler<T> = (payload: T) => void;

class Emitter<Events extends Record<string, unknown>> {
  #handlers: { [K in keyof Events]?: Set<Handler<Events[K]>> } = {};

  on<K extends keyof Events>(type: K, handler: Handler<Events[K]>): () => void {
    const handlers = (this.#handlers[type] ??= new Set());
    handlers.add(handler);
    return () => handlers.delete(handler);
  }

  emit<K extends keyof Events>(type: K, payload: Events[K]): void {
    this.#handlers[type]?.forEach((handler) => handler(payload));
  }
}
  • Events is fixed once, when the emitter is created: new Emitter<AppEvents>().
  • K is inferred at each call from the event name, so Events[K] is the payload of that event.
  • #handlers is a mapped type (they get their own topic): one optional set of handlers per event, each typed for that event's payload, with no any.
  • on returns an unsubscribe function, so callers do not have to keep the handler around.
TypeScript
const events = new Emitter<AppEvents>();

const off = events.on("cart:add", (item) => {
  console.log(item.quantity); // item: { productId: string; quantity: number }
});

events.emit("login", { userId: "u1" });
events.emit("login", { id: "u1" }); // Error: Object literal may only specify known properties, and 'id' does not exist in type '{ userId: string; }'.
events.emit("signup", {}); // Error: Argument of type '"signup"' is not assignable to parameter of type 'keyof AppEvents'.
events.emit("logout"); // Error: Expected 2 arguments, but got 1.
off();

What a reviewer would ask about

  • The constraint rejects interfaces. With interface AppEvents { … }, new Emitter<AppEvents>() fails with "Index signature for type 'string' is missing in type 'AppEvents'": interfaces do not get an implicit index signature, type aliases do. Use a type, or constrain with Events extends object, which accepts both.
  • Events without a payload still need emit("logout", undefined). Making the second argument optional only for those events takes a conditional type.
  • The types say nothing about where a payload came from. Data from outside (a WebSocket message, postMessage) has to be validated before it is emitted; the emitter only passes it on.
SeniorConcept

const type parameters and NoInfer

const type parameters

By default, inference widens literals inside arrays and objects, because such values usually change later:

TypeScript
function createNavigator<T extends readonly string[]>(paths: T) {
  return (path: T[number]) => location.assign(path);
}

const navigate = createNavigator(["/", "/about", "/pricing"]);
navigate("/abuot"); // no error: T is string[], so T[number] is string

The old fix was to ask every caller for as const. Since TypeScript 5.0 the function can ask for it itself, with a const modifier on the type parameter:

TypeScript
function createNavigator<const T extends readonly string[]>(paths: T) {
  return (path: T[number]) => location.assign(path);
}

const navigate = createNavigator(["/", "/about", "/pricing"]);
// T is readonly ["/", "/about", "/pricing"]
navigate("/about"); // OK
navigate("/abuot"); // Error: Argument of type '"/abuot"' is not assignable to parameter of type '"/" | "/about" | "/pricing"'.

T[number] is an indexed access with number: the union of the tuple's element types. Two rules from the release notes:

  • const affects only literals written in the call. const paths = ["/", "/about"]; createNavigator(paths) still gives string[], because paths was widened when it was declared.
  • Write the constraint as readonly string[], as the release notes recommend: const inference produces readonly tuples, and a readonly constraint accepts them.

NoInfer

When a type parameter appears in several parameters, each of them is an inference candidate. Sometimes one parameter should be the source of truth and the others should only be checked against it:

TypeScript
function createStreetLight<C extends string>(colors: C[], defaultColor?: C) {}

createStreetLight(["red", "yellow", "green"], "blue"); // accepted: C is "red" | "yellow" | "green" | "blue"

TypeScript 5.4 added the NoInfer<T> utility type. Wrapping a parameter's type in it removes that position from inference; the type itself stays C:

TypeScript
function createStreetLight<C extends string>(colors: C[], defaultColor?: NoInfer<C>) {}

createStreetLight(["red", "yellow", "green"], "blue"); // Error: Argument of type '"blue"' is not assignable to parameter of type '"red" | "yellow" | "green" | undefined'.

Before 5.4 the workaround was a second type parameter, D extends C, used only once.

Both examples keep literal types only because of C extends string: a constraint that includes a primitive type keeps literal candidates such as "red". An unconstrained C would be inferred as plain string, and "blue" would pass even with NoInfer.

SeniorConcept

Variance at a glance

If Dog is assignable to Animal, is Box<Dog> assignable to Box<Animal>? It depends on what Box does with its type parameter. That property is called variance, and TypeScript works it out from the structure of the type:

TypeScript
type Animal = { name: string };
type Dog = Animal & { bark(): string };

interface Getter<T> { get: () => T } // T only comes out
interface Setter<T> { set: (value: T) => void } // T only goes in

declare const getDog: Getter<Dog>;
declare const setAnimal: Setter<Animal>;
declare const setDog: Setter<Dog>;

const g: Getter<Animal> = getDog; // OK: covariant
const s1: Setter<Dog> = setAnimal; // OK: contravariant
const s2: Setter<Animal> = setDog; // Error: Type 'Setter<Dog>' is not assignable to type 'Setter<Animal>'.
  • Covariant (T in output positions): the generic type follows the direction of T. Something that produces dogs produces animals.
  • Contravariant (T in input positions): the direction flips. Something that accepts any animal also accepts a dog, but a dog handler cannot be given a cat.
  • Invariant: T goes both in and out, so neither direction is safe.

Where TypeScript is deliberately loose

Method syntax. strictFunctionTypes, part of strict, checks parameters this strictly only in function syntax. The tsconfig reference says methods are left out because many existing class hierarchies, some in the DOM, would break:

TypeScript
interface Formatter<T> { format(value: T): string } // method syntax
interface StrictFormatter<T> { format: (value: T) => string } // property syntax

declare const upper: Formatter<string>;
declare const strictUpper: StrictFormatter<string>;

const loose: Formatter<string | number> = upper; // accepted: loose.format(42) can crash
const checked: StrictFormatter<string | number> = strictUpper; // Error

Arrays. Dog[] is assignable to Animal[] even though arrays are mutable: push is a method, so its parameter is compared the loose way. const animals: Animal[] = dogs; animals.push({ name: "Tom" }) compiles and leaves an object without bark inside dogs.

What to do with this

  • Declare callbacks in your own types with property syntax, onChange: (value: T) => void, to get the strict check.
  • Accept readonly T[] when a function only reads: a readonly Animal[] parameter takes a Dog[] safely, because nothing can be pushed into it.
  • Variance annotations exist since TypeScript 4.7 (interface Producer<out T>, interface Consumer<in T>), but the handbook calls them an advanced feature for very specific problems: they do not change structural checks, and should only state the variance the structure already has. In everyday code, let TypeScript infer it.
SeniorInterview tips

Interview tips

A 30-second answer. "Generics let a function or a type take type parameters, so it works with many types and keeps the relation between them: first<T>(items: T[]): T | undefined returns the element type of whatever array it gets, where any would lose it. TypeScript usually infers the type arguments from the call. A constraint like T extends { length: number } says what a type must have, and K extends keyof T with T[K] ties a key to its value type. A type parameter that appears only once is a smell; in the return type alone, it is a disguised cast."

Questions you are likely to get

  • Generics vs any vs unknown? any turns checking off, unknown keeps it but makes the caller narrow, a generic keeps the caller's own type.
  • Write getProperty, pluck or a typed event emitter. Two type parameters, K extends keyof T, return T[K]; for the emitter, an event map type on the class and K inferred per call.
  • Why does minimumLength not compile? The signature promises the caller's own T, and a value that only matches the constraint is not a T.
  • How does inference work, and when do you pass type arguments? From the arguments, and from there into callbacks; explicitly only when there is nothing to infer from (new Map<string, User>()) or the inferred type is not the one you mean.
  • What do const type parameters and NoInfer do? Literal inference without as const at the call site (TypeScript 5.0); excluding a parameter from inference so it is only checked (TypeScript 5.4).
  • What is variance? Producers are covariant, consumers contravariant, types that do both are invariant; method parameters and arrays are the deliberately loose spots.

Mistakes that cost points

  • Adding <T> to functions where it appears once.
  • Presenting fetchJson<T>() or JSON.parse(text) as T as type safety.
  • Silencing a generic error with as T or as any instead of fixing the signature.
  • Reading extends in a constraint as class inheritance.
  • Suggesting the function can branch on T at run time. Types are erased; only values can be checked.

Senior signal

Talk about the callers. A good generic API is inferred, so callers rarely write type arguments, and its errors point at the wrong argument instead of deep inside a type. Say when you would not write a generic at all (one concrete type, or a plain union), and how you would test a shared helper's types: calls that must compile, plus calls marked // @ts-expect-error that must not. And say where the guarantee ends: at a boundary, a generic is only as true as the validation behind it.

JuniorReview checklist

What to check when reviewing generic code

Use this list when you review generic code you did not write: a teammate's pull request, a library's example, an AI assistant's suggestion. A wrong generic still compiles; the cost shows up later, as any leaking into callers or a "typed" result that nothing ever checked.

  • Does every type parameter appear at least twice in the signature, the return type included? One that appears once relates nothing: replace it with its constraint or a concrete type and see whether any call site loses a type.
  • Is a type parameter used only in the return type, as in fetchJson<T>() or parse<T>(text)? Then the caller picks T and no code checks the data: it is an unchecked cast. Look for an unknown result plus validation, or a validator parameter from which T is inferred.
  • Does the body need as T, as any or @ts-ignore to compile? Usually the signature promises more than the body delivers, like returning { length: minimum } from a function that promises the caller's own T. Fix the signature or the body, not the error.
  • Does the function return the type parameter, not its constraint? A return type of { length: number } for an argument of type T throws away the caller's type. Hover a call in the editor: a string argument should give a string back.
  • Do key parameters use K extends keyof T, and values T[K]? A key: string with a cast, or a key: keyof T that returns the union of all property types, breaks the link between a key and its value. A misspelled key at a call site should not compile.
  • Are empty collections given type arguments? new Map() is Map<any, any>, so nothing stored in it is checked. Search the diff for new Map() and new Set() without type arguments.
  • Do functions that only read an array take readonly T[], and are callbacks in your own types written with property syntax? Arrays and method parameters are checked loosely; these two habits let the compiler catch writes through a wider type and handlers that accept too little.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    7 questions