Thuta Learning
TypeScript
AdvancedProgrammingIntermediate

Generics

TypeScriptLesson 1930 min

What you'll walk away with

  • Declare a type parameter like <T> and let TypeScript infer it from the arguments
  • Explain why a generic keeps type information that any throws away
  • Restrict a type parameter with extends, including K extends keyof T
  • Recognise when a generic is unnecessary and a plain type is clearer

Explain it simply

Generics in plain language

A generic is a function or type with a blank in it. Instead of writing one version for numbers and another for strings, you write one version with a placeholder, usually called T, and the caller's values fill that blank in. The placeholder is a type, not a value, so it disappears when the code runs.

Think of a labelled storage box. A box that says 'contains anything' is useless, because when you open it you have no idea what is inside. A generic box says 'contains the same kind of thing you put in', so if you stored books you get books back. That 'same kind' promise is the whole point of generics.

Problem → Why → Solution

The problem: one helper, many types

You need a helper that returns the first item of a list. You write it for numbers, then the profile page needs it for strings, and the order page needs it for Order objects. Copying the function three times is tedious, so you reach for any. The code compiles, but now every caller gets any back: misspell a property or call a method that does not exist, and the compiler says nothing until the app crashes.

first-item-any.ts
function firstItem(items: any[]): any {
  return items[0];
}

const price = firstItem([9.99, 4.5]);
console.log(price.toUpperCase()); // compiles, then crashes at runtime

const name = firstItem(["Ada", "Linus"]);
console.log(name.lenght); // typo compiles too and prints undefined

Why any is not the answer

any does not mean 'some type I will remember'; it means 'stop checking'. The function knows its input is an array of numbers, but that knowledge is thrown away at the return. A generic keeps it: the return type is tied to the element type of the argument, so a number array returns a number and the compiler can catch both bugs above.

Core concept: type parameters carry types through

A type parameter is declared in angle brackets right after the function name: function firstItem<T>(items: T[]): T | undefined. Read it as 'for some type T, this function takes an array of T and returns a T or undefined'. T is a variable for types. Each call picks a concrete T, and every place T appears in the signature is replaced with that same type.

Usually you never write the type yourself. When you call firstItem([1, 2, 3]), TypeScript sees number[] and infers T = number, so the result is number | undefined. You can pass the type explicitly, firstItem<string>([]), when there is nothing to infer from, such as an empty array. The | undefined in the return type is honest: an empty array has no first element, and index access does not check that for you.

An unconstrained T can be anything, so inside the function you may only do things that work for every type. To use a property, add a constraint with extends: <T extends { length: number }> means 'any T, as long as it has a numeric length'. Strings, arrays and your own objects qualify; numbers do not. The most useful constraint pairs two parameters: <T, K extends keyof T> says K must be one of T's keys, and the return type T[K] is exactly the type of that property.

DeclarationMeaning
<T>any type; only operations valid for every type
<T extends { id: string }>any type that has a string id
<T, K extends keyof T>K must be a key of T; T[K] is that value's type
<T = string>a default used when T is not given and cannot be inferred

Generics are not only for functions. Types, interfaces and classes take parameters too: Array<T>, Promise<T> and Map<K, V> are generic types from the standard library, and type ApiResponse<T> = { data: T; error: string | null } lets every endpoint share one shape. Like every type, T is erased at compile time, so you cannot write typeof T or new T() inside the function.

Generics as a fill-in-the-blank contract
  1. Declare a blank: <T>
  2. Use T in params and return type
  3. Caller's arguments fill in T
  4. Every T becomes that same type

If T appears only once in a signature, it links nothing; a plain type (or unknown) is usually clearer.

General pattern

typescript
function name<T>(param: T[]): T | undefined { ... }

function name<T extends Shape>(param: T): T { ... }

function name<T, K extends keyof T>(obj: T, key: K): T[K] { ... }

type Wrapper<T> = { value: T };

Declare type parameters in angle brackets, use them in the parameters and the return type, and add extends only when the body needs to rely on some property of T.

Worked example: one helper for every array type

The function below is written once and called with three different element types. Watch the comments: they show what TypeScript infers for T at each call. The last line proves the result really is a number, because a number method is allowed on it after an optional-chaining check.

generics.ts
function getFirstElement<T>(arr: T[]): T | undefined {
  return arr[0];
}

const firstNumber = getFirstElement([1, 2, 3]); // T = number
const firstString = getFirstElement(["a", "b", "c"]); // T = string
const fromEmpty = getFirstElement<boolean>([]); // T = boolean (explicit)

console.log(firstNumber, firstString, fromEmpty);
console.log(firstNumber?.toFixed(1));

Code breakdown

  1. Declare Tfunction getFirstElement<T>(arr: T[]): T | undefined {

    <T> introduces the type parameter. The parameter is an array of T and the result is T or undefined, so input and output are linked.

  2. Infer from a valueconst firstNumber = getFirstElement([1, 2, 3]); // T = number

    TypeScript sees number[] and fills T with number; no angle brackets are needed at the call site.

  3. Explicit type argumentconst fromEmpty = getFirstElement<boolean>([]); // T = boolean (explicit)

    An empty array gives TypeScript nothing to infer from, so the call passes boolean explicitly. At runtime it returns undefined, which the return type already warned about.

  4. Use the typed resultconsole.log(firstNumber?.toFixed(1));

    Because the result is number | undefined, ?. is needed before calling toFixed. With any you would get no warning; here the compiler knows exactly which methods exist.

You should see
1 a undefined
1.0

Constraints: asking T for a minimum shape

Add a constraint when the function body needs to know something about T. Below, longest has to compare lengths, and getProperty wants to accept only keys that really exist on the object.

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

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

const user = { id: 7, name: "Ada" };
const id = getProperty(user, "id"); // number
const name = getProperty(user, "name"); // string

console.log(longest([1, 2], [3]), longest("TypeScript", "Go"), id, name);
// getProperty(user, "email"); // error: "email" is not a key of user
// longest(10, 20); // error: number has no length property

The constraint is checked at the call site. longest(10, 20) fails because numbers have no length, and getProperty(user, "email") fails because "email" is not in keyof typeof user. Inside the body, the constraint is what makes a.length legal; without it, T could be a number and the compiler rejects the property access.

In real projects

Where generics show up in real projects

You use generics every day before you write one. Promise<User> is what an async function returns, Array<T> and Map<K, V> are generic collections, and React's useState<T> keeps a piece of state typed. Writing your own pays off at the seams of an application, where the same logic handles many data shapes.

  • API response wrappers: type ApiResponse<T> = { data: T; error: string | null } gives every endpoint the same envelope while keeping each payload typed. Checking the JSON at runtime is a separate job (lesson 22).
  • Repositories and caches: a class Repository<T extends { id: string }> can store, find and delete users, orders or products with one implementation, and the constraint guarantees every item has an id to look up.
  • Utility functions such as groupBy, uniqueBy or pick are written once with type parameters and reused across the codebase without losing the types of the items they process.

Common mistakes

Common mistakes with generics

Using any or unknown[] where a generic belongs

function first(items: unknown[]): unknown is type-safe but useless: callers must cast the result. If the output should have the same type as the input, that relationship needs a type parameter.

Adding a type parameter that links nothing

function log<T>(value: T): void uses T only once, so it behaves exactly like (value: unknown). A return-only generic such as parse<T>(json: string): T is worse: it looks safe but is a hidden type assertion, because nothing checks that the JSON is a T.

Forgetting the constraint, then casting

When the body reports Property 'length' does not exist on type 'T', the fix is <T extends { length: number }>, not (a as any).length. The constraint documents the requirement and forces callers to pass valid values.

Best practices

Best practices

  • Let inference do the work; write explicit type arguments only when there is nothing to infer from.
  • Name parameters by role when there are several: TItem, TKey and TResult read better than T, U and V.
  • Use the loosest constraint the body really needs, so the function stays reusable.
  • Prefer a plain parameter type when a type parameter would appear only once.

Mini challenge

Mini challenge: pluck and findById

Write two small generic helpers for a list of records. pluck takes an array and a key and returns the values of that key, typed precisely. findById looks up an item by its id, but only accepts arrays whose items actually have a numeric id.

  • pluck<T, K extends keyof T>(items: T[], key: K) returns T[K][]
  • findById accepts only items with id: number and returns T | undefined
  • Call both with a products array and print the results
  • Add one commented-out call that should fail to compile, and explain why
pluck.ts
type Product = { id: number; name: string; price: number };

const products: Product[] = [
  { id: 1, name: "Keyboard", price: 49 },
  { id: 2, name: "Mouse", price: 19 },
];

// TODO: declare the type parameters and the return type
function pluck(items, key) {
  // TODO: return the value of `key` for every item
}

// TODO: constrain T so that every item must have id: number
function findById(items, id: number) {
  // TODO: return the matching item or undefined
}

// TODO: print pluck(products, "name") and the price of product 2

Expected: pluck prints [ 'Keyboard', 'Mouse' ] and its type is string[]; findById(products, 2)?.price prints 19; pluck(products, "colour") does not compile.

Show hint

Start from the signatures: K extends keyof T makes the key safe and T[K] gives its value type. For findById, T extends { id: number } is enough; Array.prototype.find already returns T | undefined.

Show solution
pluck.ts
type Product = { id: number; name: string; price: number };

const products: Product[] = [
  { id: 1, name: "Keyboard", price: 49 },
  { id: 2, name: "Mouse", price: 19 },
];

function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
  return items.map((item) => item[key]);
}

function findById<T extends { id: number }>(items: T[], id: number): T | undefined {
  return items.find((item) => item.id === id);
}

const names = pluck(products, "name"); // string[]
const prices = pluck(products, "price"); // number[]
console.log(names, prices);
console.log(findById(products, 2)?.price);
console.log(findById(products, 99));
// pluck(products, "colour"); // error: "colour" is not a key of Product

Quick quiz 1 / 3

Given function getFirstElement<T>(arr: T[]): T | undefined, what is the type of x in const x = getFirstElement([true, false])?

Quick quiz 2 / 3

Why does this fail to compile? function longest<T>(a: T, b: T) { return a.length >= b.length ? a : b; }

Quick quiz 3 / 3

Which signature best keeps the link between the key you pass and the type you get back?

What to remember

  • A type parameter like <T> is a placeholder for a type that each call fills in, usually by inference.
  • Generics keep the relationship between input and output types; any and unknown throw it away.
  • Add constraints with extends (for example K extends keyof T) when the body relies on a shape.
  • If T appears only once, or only in the return type, the generic is probably unnecessary or unsafe.

TypeScript Handbook — TypeScript

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Generics | Thuta Learning