Skip to content

Lesson 1 of 9 · 22m

Generics Are Type Parameters, Not Syntax Noise

The mental model behind generics: types as inputs and outputs, inference as a solver, and why good generic APIs disappear at the call site.

The day generics stop looking like noise is the day you realize they are function parameters — just parameters whose values are types. function identity<T>(value: T): T is not ceremony. It says: give me a type and a value of that type, and I will hand you back the same type. That relationship is the entire point.

Types are relationships, not labels

A junior engineer writes types as labels: name: string, age: number. A senior engineer writes types as relationships: this return value has the same element type as that array; this key must exist on that object; this event name determines that payload shape.

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

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

T is a variable bound at the call site. TypeScript inspects the arguments, solves for T, and checks whether the returned type follows. You rarely write <number> explicitly because inference does the boring work.

Type parameters should earn their place

A type parameter that appears only once is usually hiding a mistake:

// suspicious: T is not related to anything else
function parse<T>(input: string): T {
  return JSON.parse(input) as T;
}

const user = parse<User>(body); // compiles even if body is not a User

That function is a type assertion wearing a generic costume. It says "trust me" at exactly the place the compiler should be skeptical. In real systems, use generics to preserve information across a boundary, not to manufacture certainty.

Good generic APIs disappear

The best generic API feels untyped at the call site:

const users = groupBy(records, (record) => record.region);
// users: Record<string, Record[]>

Callers should not need to understand the internal machinery. The type parameters are there so the compiler can remember what the programmer meant after values pass through a pipe, a cache, or a database row mapper.

Field notes

  • If every call site writes the type arguments explicitly, inference has failed or the API shape is wrong.
  • A generic that is immediately cast with as is not type safety; it is type theater.
  • Prefer readonly T[] for inputs you do not mutate. It accepts both mutable and immutable arrays.
  • When inference collapses to unknown, treat it as a clue: the compiler could not find enough evidence, and neither can a reviewer.

Was this lesson helpful?

Sign in to rate