Skip to content

Generics

A generic is a type parameter: a placeholder filled in by the caller or inferred from the arguments, so one implementation serves many types without losing information. Generics are the difference between function first(xs: any[]): any and a function whose return type is derived from its input.

“Generics parameterise types the way functions parameterise values. You declare a type parameter on a function, class, interface or alias, optionally constrain it with extends, and TypeScript infers it from the call site. The important property is that information flows: identity<T>(x: T): T preserves the input type, and pick<T, K extends keyof T> ties the key set to the object. On top of that, mapped types transform every property of a type, and conditional types choose between two types based on an assignability check — which is how the utility types are built.”

generics.ts
function identity<T>(value: T): T { return value; }
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
const a = first([1, 2, 3]); // number | undefined
const b = first(['x', 'y']); // string | undefined

Inference reads the argument. When it cannot decide, the parameter falls back to unknown or to its default. If you have to specify the type at every call site, the generic is not earning its keep.

Note readonly T[]: it accepts mutable and readonly arrays. Accepting T[] would reject a readonly input for no reason.

extends on a type parameter sets the minimum shape.

function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
const users = [{ id: '1', name: 'Ada' }, { id: '2', name: 'Alan' }];
pluck(users, 'name'); // string[]
// pluck(users, 'age'); // error: 'age' is not a key of T

T[K] is an indexed access type: the type of property K on T. With keyof T it is the backbone of type-safe property access.

repository.ts
interface Repository<T, Id = string> {
findById(id: Id): Promise<T | null>;
save(entity: T): Promise<T>;
}
class InMemoryRepository<T extends { id: string }> implements Repository<T> {
#items = new Map<string, T>();
async findById(id: string) { return this.#items.get(id) ?? null; }
async save(entity: T) { this.#items.set(entity.id, entity); return entity; }
}

A default type parameter (Id = string) keeps the common case short. The constraint T extends { id: string } documents why the body may use entity.id — the constraint is the contract the implementation relies on.

type User = { id: string; name: string; age: number };
type Keys = keyof User; // 'id' | 'name' | 'age'
type NameType = User['name']; // string
type Values = User[keyof User]; // string | number

This is how libraries type get(obj, 'a.b.c') and setState({ name: 'x' }).

A mapped type iterates over the keys of another type.

mapped.ts
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
// Key remapping with `as`:
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };
type UserGetters = Getters<{ name: string; age: number }>;
// { getName: () => string; getAge: () => number }

Modifiers can be added or removed: { [K in keyof T]-?: T[K] } strips optionality, which is how Required is defined.

type IsString<T> = T extends string ? true : false;
type ElementType<T> = T extends readonly (infer U)[] ? U : never;
type Flatten<T> = T extends (infer U)[] ? Flatten<U> : T;
type N = Flatten<number[][][]>; // number

infer introduces a type variable inside the extends clause and captures whatever matched. This is how ReturnType, Parameters and Awaited work.

Conditional types distribute over naked type parameters: with a union T, the check applies per member. Wrap in a tuple to opt out:

type ToArray<T> = T extends unknown ? T[] : never;
type A = ToArray<string | number>; // string[] | number[] (distributed)
type ToArray2<T> = [T] extends [unknown] ? T[] : never;
type B = ToArray2<string | number>; // (string | number)[] (not distributed)
patterns.ts
// Typed event map
type Handler<E> = { [K in keyof E]: (payload: E[K]) => void };
// Result instead of throwing
type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };
// Branded primitives to stop mixing ids
type UserId = string & { readonly __brand: 'UserId' };
// Exhaustiveness
function assertNever(x: never): never { throw new Error(`Unexpected: ${JSON.stringify(x)}`); }

Branded types answer “how do I stop passing an OrderId where a UserId is expected” when both are strings. The brand is erased at runtime, so it is compile-time discipline only.

  1. When is a generic worse than a union type?
  2. Why does a conditional type distribute, and how do you stop it?
  3. What is the difference between T extends U in a constraint and in a conditional type?
  4. How do you constrain a key parameter to only string-valued properties?
  • Generic parameters that appear once. Ceremony with no safety.
  • Using any inside a generic body. You defeat the parameter you declared.
  • Forgetting readonly on array parameters. It needlessly rejects readonly inputs.
  • Deeply nested conditional types. Unreadable, with terrible error messages; prefer a union or an overload.
  • Assuming inference works from the return type. It works from arguments and contextual positions.