1. Concept library
  2. JavaScript & TypeScript
  3. Module 5: Generics in practice

Concept

Type parameters

A generic function or type takes a type as a parameter, so one definition works for many types without losing track of which one. The caller usually never writes the parameter; it is inferred.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what a type parameter is and how the caller's type is inferred
  2. Write a generic function that keeps the element type of its input
  3. Spot a type parameter used only once that constrains nothing

In practice

A few lines that show Type parameters doing its job.

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

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

type ApiResponse<T> = { ok: true; data: T } | { ok: false; error: string };

The common mistake

Watch for

Adding a type parameter that is used only once, such as function log<T>(value: T): void. It constrains nothing and could be unknown; a generic earns its keep by linking two places.

What to know first

Your roadmap puts these before Type parameters, unless you already know them.

How it stays learned

Once a session shows you understand Type parameters, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Type parameters.

Next in the modulekeyof constraints →