10LOC

#type-safety

TypeScriptadvanced

A type-safe event emitter keyed by an event-name-to-payload map

type EventMap = Record<string, unknown>;

export class TypedEmitter<Events extends EventMap> {
  private listeners: { [K in keyof Events]?: Array<(payload: Events[K]) => void> } = {};

Make on() and emit() reject mismatched event names and payloads at compile time, from one map type instead of per-event overloads.

TypeScriptintermediate

Branded types to stop mixing UserId and OrderId

type Brand<T, Name extends string> = T & { readonly __brand: Name };

export type UserId = Brand<string, "UserId">;
export type OrderId = Brand<string, "OrderId">;

Give two string IDs distinct types so passing one where the other belongs is a compile error, at zero runtime cost.