Menu

Generic Patterns in Practice

Lesson 5: Generic Patterns in Practice

Which patterns appear in real projects?

Pattern Problem it solves
Result<T, E> Return success or failure without throwing
Typed fetch helper One function for every endpoint, typed per call
Typed event emitter Event names and payloads checked together
Generic React components Lists, tables, and selects for any item type (Module 10)

Example: Result type

type Result<T, E = string> = { ok: true; value: T } | { ok: false; error: E };

function applyCoupon(total: number, code: string): Result<number> {
  if (code !== 'FRESH10') return { ok: false, error: 'Invalid coupon' };
  return { ok: true, value: Math.round(total * 0.9) };
}

const result = applyCoupon(95700, 'FRESH10');
if (result.ok) console.log(result.value); // number
else console.log(result.error);           // string

Example: typed event emitter

type QuickCartEvents = {
  'cart:add': { productId: string; quantity: number };
  'order:placed': { orderId: string; total: number };
  'order:cancelled': { orderId: string; reason: string };
};

class TypedEmitter<Events extends Record<string, unknown>> {
  private listeners: { [K in keyof Events]?: ((payload: Events[K]) => void)[] } = {};

  on<K extends keyof Events>(event: K, listener: (payload: Events[K]) => void): void {
    (this.listeners[event] ??= []).push(listener);
  }

  emit<K extends keyof Events>(event: K, payload: Events[K]): void {
    this.listeners[event]?.forEach((listener) => listener(payload));
  }
}

const events = new TypedEmitter<QuickCartEvents>();
events.on('order:placed', ({ orderId, total }) => console.log(orderId, total));
events.emit('order:placed', { orderId: 'QC-1042', total: 95700 }); // OK
events.emit('order:placed', { orderId: 'QC-1042' });
// Error: Property 'total' is missing.

How it works

  • Result<T, E> makes failure part of the type, so callers cannot forget to handle it.
  • In the emitter, K extends keyof Events links the event name to its payload type. Changing a payload updates every listener and every emit call.
  • { [K in keyof Events]?: ... } is a mapped type, covered in Module 8.

When not to use generics:

Situation Better choice
The function works with one specific type Use that type
The type parameter appears only once Use unknown or the concrete type
Callers must always pass type arguments manually Reconsider the design

Common mistakes

Mistake Effect Fix
Over-generic code "for the future" Hard to read and debug Add generics when a second use appears
Generic fetch helpers that trust the response type Wrong data typed as correct Validate the response with a schema (Module 10)
Mixing throw and Result randomly Inconsistent error handling Choose one style per layer

Key takeaways

  • Result types, typed fetch helpers, and typed emitters are the most common generic patterns.
  • Use generics to link types together, not just to look flexible.

Try it: Write a generic fetchJson<T>(url: string): Promise<Result<T>> that returns { ok: false } for network errors and non-OK responses instead of throwing.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details