Complete Tutorial

Master TypeScript
Generics

From zero to advanced patterns — with visual examples, comparisons, and quizzes to lock in your understanding.

12 Lessons Interactive Quizzes Real Patterns
01

What Are Generics?

Generics let you write reusable, type-safe code that works with many types instead of just one. Think of them as type variables — placeholders for types that are filled in when the code is actually used.

💡
The core idea: Instead of writing the same function 10 times for 10 different types, you write it once with a type parameter <T> — and TypeScript figures out the type automatically when you call it.
WITHOUT GENERICS (repetitive)
// Must write separate functions
// for each type — ugly!
function getFirstNumber(
  arr: number[]
): number {
  return arr[0];
}

function getFirstString(
  arr: string[]
): string {
  return arr[0];
}
// ... repeat for every type
WITH GENERICS (elegant)
// One function handles ALL types
// with full type safety!
function getFirst<T>(
  arr: T[]
): T {
  return arr[0];
}

// Works for any type
getFirst([1, 2, 3]);      // → number
getFirst(['a', 'b']);    // → string
getFirst([true, false]); // → boolean
Quick Check
What problem do generics solve in TypeScript?
02

Basic Syntax

Generics use angle brackets <T> to declare type parameters. By convention, single uppercase letters like T, U, V are used, but you can use any name.

function identity<T>(value: T): T { return value; }
function keyword
identity function name
<T> type parameter
value: T typed parameter
: T return type
basic-generics.ts TypeScript
// ── 1. Generic Function ──────────────────────────
function identity<T>(value: T): T {
  return value;
}

// TypeScript INFERS the type automatically
const a = identity(42);         // T = number → returns number
const b = identity("hello");    // T = string → returns string
const c = identity({ x: 1 });   // T = {x:number} → same type back

// You can also pass the type EXPLICITLY
const d = identity<string>("world"); // explicit call

// ── 2. Generic Arrow Function ────────────────────
const wrap = <T>(item: T): T[] => [item];

wrap(5);       // → number[]
wrap("hi");   // → string[]
✦
Type Inference: TypeScript can usually figure out T from the argument you pass. You only need explicit <T> when inference isn't possible.
Quick Check
What is the type of result here?
const result = identity(true);
03

Multiple Type Parameters

You can declare multiple type parameters separated by commas. Each one is independent. This is useful for functions that relate two different types.

multiple-params.ts TypeScript
// ── Two type parameters ──────────────────────────
function pair<A, B>(first: A, second: B): [A, B] {
  return [first, second];
}

pair(1, "hello");         // [number, string]
pair(true, { id: 5 });   // [boolean, {id:number}]

// ── Converting between types ─────────────────────
function transform<Input, Output>(
  value: Input,
  converter: (v: Input) => Output
): Output {
  return converter(value);
}

// number → string
const str = transform(42, (n) => n.toString());
// str: string ✓

// string → number
const num = transform("99", (s) => parseInt(s));
// num: number ✓

// ── Swap tuple elements ──────────────────────────
function swap<X, Y>(tuple: [X, Y]): [Y, X] {
  return [tuple[1], tuple[0]];
}

swap(["hello", 42]); // → [42, "hello"] typed [number, string]
04

Generic Constraints

Sometimes you want to restrict what types T can be. Use extends to add constraints — telling TypeScript "T must have at least these properties".

⚠
Without constraints, TypeScript won't let you access any properties of T because it could be anything. Constraints unlock specific capabilities.
constraints.ts TypeScript
// ── Basic constraint ─────────────────────────────
// T must have a .length property
function getLength<T extends { length: number }>(item: T): number {
  return item.length; // ✓ safe to access
}

getLength("hello");    // ✓ strings have .length
getLength([1, 2, 3]); // ✓ arrays have .length
getLength(42);        // ✗ Error: number has no .length

// ── Interface constraint ─────────────────────────
interface HasId {
  id: number;
}

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

const users = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }];
findById(users, 1); // → { id: 1, name: "Alice" }

// ── keyof constraint ─────────────────────────────
// K must be a valid key of T
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const person = { name: "Alice", age: 30 };
getProperty(person, "name");   // ✓ → "Alice" (string)
getProperty(person, "age");    // ✓ → 30 (number)
getProperty(person, "email");  // ✗ Error: not a valid key!
Quick Check
What does T extends HasId mean?
05

Default Types

Like default parameters in functions, type parameters can have defaults. If no type is provided, TypeScript uses the default.

default-types.ts TypeScript
// ── Default type parameter ───────────────────────
interface ApiResponse<T = unknown> {
  data: T;
  status: number;
  message: string;
}

// With explicit type
const userResponse: ApiResponse<{ name: string; id: number }> = {
  data: { name: "Alice", id: 1 },
  status: 200,
  message: "OK",
};

// Without type — uses default 'unknown'
const rawResponse: ApiResponse = {
  data: null,
  status: 404,
  message: "Not Found",
};

// ── Default + Constraint combined ────────────────
function createState<T = string>(initial: T): { value: T; set: (v: T) => void } {
  let state = initial;
  return {
    get value() { return state; },
    set(v) { state = v; },
  };
}

const name = createState("Alice"); // T = string (default)
const count = createState(0);      // T = number (inferred)
06

Generic Interfaces

Generic interfaces describe shapes of objects that work with multiple types. They're excellent for modeling data structures and API contracts.

generic-interfaces.ts TypeScript
// ── Generic Stack data structure ─────────────────
interface Stack<T> {
  push(item: T): void;
  pop(): T | undefined;
  peek(): T | undefined;
  size: number;
}

// Implementation
class ArrayStack<T> implements Stack<T> {
  private items: T[] = [];
  push(item: T) { this.items.push(item); }
  pop()  { return this.items.pop(); }
  peek() { return this.items.at(-1); }
  get size() { return this.items.length; }
}

const numStack = new ArrayStack<number>();
numStack.push(1); numStack.push(2); numStack.push(3);
numStack.pop();   // → 3 (type: number)

// ── Generic Repository pattern ───────────────────
interface Repository<T extends { id: number }> {
  findById(id: number): T | undefined;
  findAll(): T[];
  save(item: T): T;
  delete(id: number): boolean;
}
07

Generic Classes

Generic classes are powerhouses for building reusable data structures like stacks, queues, caches, and event emitters — all with full type safety.

generic-classes.ts TypeScript
// ── Type-safe Cache ──────────────────────────────
class Cache<K extends string | number, V> {
  private store = new Map<K, V>();

  set(key: K, value: V): this {
    this.store.set(key, value);
    return this; // enables chaining
  }

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

  has(key: K): boolean {
    return this.store.has(key);
  }
}

// String keys, User values
const userCache = new Cache<string, { name: string; age: number }>();
userCache
  .set("alice", { name: "Alice", age: 30 })
  .set("bob",   { name: "Bob",   age: 25 });

userCache.get("alice")?.name; // → "Alice"

// ── Generic EventEmitter ─────────────────────────
class TypedEmitter<Events extends Record<string, unknown>> {
  private handlers = {} as {
    [K in keyof Events]?: ((data: Events[K]) => void)[]
  };

  on<K extends keyof Events>(event: K, handler: (data: Events[K]) => void) {
    (this.handlers[event] ??= []).push(handler);
  }

  emit<K extends keyof Events>(event: K, data: Events[K]) {
    this.handlers[event]?.forEach(h => h(data));
  }
}

type AppEvents = { login: { userId: string }; logout: void };
const emitter = new TypedEmitter<AppEvents>();
emitter.on("login", ({ userId }) => console.log(userId)); // fully typed!
✓

Foundations & Intermediate Complete

  • You understand type parameters and inference
  • You can write constrained generics
  • You can build generic interfaces and classes
08

keyof & Indexed Access

keyof T produces a union of all keys of type T. Combined with indexed access types T[K], this creates powerful type relationships.

keyof-types.ts TypeScript
type User = { id: number; name: string; email: string };

// keyof creates a union of keys
type UserKeys = keyof User; // "id" | "name" | "email"

// Indexed access gets the value type
type NameType  = User["name"];  // string
type IdType    = User["id"];    // number
type AnyValue  = User[keyof User]; // number | string

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

const users: User[] = [
  { id: 1, name: "Alice", email: "a@x.com" },
  { id: 2, name: "Bob",   email: "b@x.com" },
];

const names  = pluck(users, "name");  // string[]
const ids    = pluck(users, "id");    // number[]
// pluck(users, "city") ← Error! "city" is not a key of User

// ── Type-safe object update ──────────────────────
function updateField<T, K extends keyof T>(
  obj: T, key: K, value: T[K]
): T {
  return { ...obj, [key]: value };
}

const updated = updateField(users[0], "name", "Alicia"); // ✓
// updateField(users[0], "name", 42) ← Error! number ≠ string
09

Conditional Types

Conditional types let you write type-level if/else logic. The syntax mirrors a ternary operator but operates on types.

Syntax Pattern
T extends U ? X : Y
"If T is assignable to U, result is X; otherwise result is Y"
conditional-types.ts TypeScript
// ── Basic conditional type ───────────────────────
type IsString<T> = T extends string ? true : false;

type A = IsString<string>;   // true
type B = IsString<number>;   // false

// ── NonNullable — remove null/undefined ──────────
type NonNull<T> = T extends null | undefined ? never : T;

type C = NonNull<string | null>;   // string
type D = NonNull<number | undefined>; // number

// ── Flatten arrays one level ─────────────────────
type Flatten<T> = T extends (infer U)[] ? U : T;

type E = Flatten<number[]>;   // number
type F = Flatten<string>;     // string (not an array, unchanged)

// ── Distributive conditional types ───────────────
// Automatically applies to each union member!
type ToArray<T> = T extends unknown ? T[] : never;

type G = ToArray<string | number>;
// → string[] | number[] (distributed!)
Quick Check
What is the result of Flatten<boolean[]>?
10

Built-in Utility Types

TypeScript ships with powerful generic utility types that transform existing types. These are used constantly in real codebases.

utility-types.ts TypeScript
type User = { id: number; name: string; email: string; age: number };

// Partial<T> — all props optional
type UserUpdate  = Partial<User>;
// { id?: number; name?: string; email?: string; age?: number }

// Required<T> — all props required
type FullUser    = Required<UserUpdate>;
// { id: number; name: string; email: string; age: number }

// Readonly<T> — all props readonly
type FrozenUser  = Readonly<User>;
// frozenUser.name = "..." ← Error!

// Pick<T, K> — keep only selected keys
type UserPreview = Pick<User, "id" | "name">;
// { id: number; name: string }

// Omit<T, K> — remove selected keys
type PublicUser  = Omit<User, "email">;
// { id: number; name: string; age: number }

// Record<K, V> — object with K keys, V values
type UserMap     = Record<string, User>;
// { [key: string]: User }

// Exclude<T, U> — remove from union
type NotString   = Exclude<string | number | boolean, string>;
// number | boolean

// Extract<T, U> — keep matching types
type Strings     = Extract<string | number | boolean, string>;
// string

// ReturnType<T> — get a function's return type
function getUser() { return { id: 1, name: "Alice" }; }
type UserResult  = ReturnType<typeof getUser>;
// { id: number; name: string }

// Parameters<T> — get a function's param types as tuple
function saveUser(id: number, name: string) {}
type SaveParams  = Parameters<typeof saveUser>;
// [id: number, name: string]
11

The infer Keyword

The infer keyword is used inside conditional types to extract and capture a type from another type — like pattern matching for types.

🔍
Mental model: infer U says "if the pattern matches, capture the matched type as U". It can only be used inside the extends condition of a conditional type.
infer-keyword.ts TypeScript
// ── Extract Promise value type ───────────────────
type Awaited<T> = T extends Promise<infer U> ? U : T;

type A = Awaited<Promise<string>>;  // string
type B = Awaited<Promise<number>>;  // number
type C = Awaited<boolean>;           // boolean (not a promise)

// ── Extract array element type ───────────────────
type Element<T> = T extends (infer U)[] ? U : never;

type D = Element<string[]>;  // string
type E = Element<number[]>;  // number

// ── Extract first param of a function ────────────
type FirstParam<T> = T extends (first: infer F, ...rest: any[]) => any
  ? F
  : never;

type F1 = FirstParam<(x: number, y: string) => void>; // number
type F2 = FirstParam<(name: string) => boolean>;     // string
12

Real-world Patterns

Here are battle-tested patterns you'll see in production TypeScript code — from API clients to form validators.

real-world-patterns.ts TypeScript
// ── 1. Generic API Client ────────────────────────
async function apiFetch<T>(url: string): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) throw new Error(res.statusText);
  return res.json() as Promise<T>;
}

interface Product { id: number; name: string; price: number }
const product = await apiFetch<Product>("/api/products/1");
// product.name ← ✓ fully typed

// ── 2. Deep Readonly ─────────────────────────────
type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object
    ? DeepReadonly<T[K]>
    : T[K];
};

// ── 3. Builder pattern ───────────────────────────
class QueryBuilder<T> {
  private filters: Partial<T> = {};
  private _limit = 100;

  where(filter: Partial<T>): this {
    this.filters = { ...this.filters, ...filter };
    return this;
  }

  limit(n: number): this {
    this._limit = n;
    return this;
  }

  build(): { filters: Partial<T>; limit: number } {
    return { filters: this.filters, limit: this._limit };
  }
}

interface UserQuery { name: string; age: number; active: boolean }
const query = new QueryBuilder<UserQuery>()
  .where({ active: true })
  .limit(10)
  .build();

// ── 4. useLocalStorage hook (React-style) ────────
function useLocalStorage<T>(
  key: string,
  initialValue: T
): [T, (value: T) => void] {
  const stored = localStorage.getItem(key);
  const initial: T = stored ? JSON.parse(stored) : initialValue;
  const setValue = (value: T) => {
    localStorage.setItem(key, JSON.stringify(value));
  };
  return [initial, setValue];
}

const [theme, setTheme] = useLocalStorage<"light" | "dark">("theme", "light");
★

You've reached mastery level!

  • Conditional types & infer for advanced transformations
  • All essential utility types (Partial, Pick, Omit, Record...)
  • Real-world patterns: API clients, builders, hooks
★

Quick Cheatsheet

Syntax Meaning
function f<T>(x: T): TGeneric function — T is inferred from the argument
f<string>("hello")Explicit type parameter — override inference
T extends SomeTypeConstraint — T must be assignable to SomeType
T extends U ? X : YConditional type — type-level if/else
keyof TUnion of all keys of T: "id" | "name" | ...
T[K]Indexed access — value type of key K in T
infer UCapture a matched type inside a conditional
Partial<T>All properties of T become optional
Required<T>All properties of T become required
Readonly<T>All properties of T become readonly
Pick<T, K>New type with only keys K from T
Omit<T, K>New type with keys K removed from T
Record<K, V>Object type with keys K and values V
Exclude<T, U>Remove U from union T
Extract<T, U>Keep only members of T assignable to U
ReturnType<F>Return type of function F
Parameters<F>Parameter types of function F as a tuple
{ [K in keyof T]: ... }Mapped type — transform all properties of T