Event Sourcing Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Event Sourcing runs in O(1) append time and O(n) space, in TypeScript as in every other language.
- ✓The runtime is JavaScript's, so the stdlib contribution is the type layer: a discriminated union of readonly object types keyed on a literal type field, Extract<DomainEvent, {type:"deposited"}> to name one variant, satisfies (TS 4.9+) to check an upcast table without widening it, and branded types like string & {readonly __id: unique symbol} to stop a StreamId being passed where a version goes.
- ✓The non-negotiable is an assertNever(x: never) in the default arm of every fold, so adding an event variant is a compile error at every switch instead of a runtime surprise.
- ✓The TypeScript trap: Types erase completely, so the annotation on a deserialised event is a claim, not a check.
- ✓Erasure means zero runtime overhead: performance is byte-for-byte JavaScript's, so the V8 hidden-class and GC notes apply unchanged.
What Event Sourcing actually is
Event Sourcing in TypeScript: what you actually reach for
TypeScript implementation
type StreamId = string & { readonly __brand: unique symbol }; // erased at runtime
type Deposited = { readonly type: "deposited"; readonly cents: number };
type Withdrawn = { readonly type: "withdrawn"; readonly cents: number };
type DomainEvent = Deposited | Withdrawn;
// reachable at runtime even though the compiler proved this arm impossible
const assertNever = (x: never): never => {
throw new Error(`unhandled event: ${JSON.stringify(x)}`);
};
function apply(balance: number, e: DomainEvent): number {
switch (e.type) {
case "deposited": return balance + e.cents;
case "withdrawn": return balance - e.cents;
default: return assertNever(e); // add a variant -> this line stops compiling
}
}
// upcasting: a total function per hop, so tsc proves every old shape is handled
type StoredV1 = { type: "deposited"; amount: number; v: 1 };
const upcastV1 = (e: StoredV1): Deposited =>
({ type: "deposited", cents: Math.round(e.amount * 100) });
// this is a LIE with no runtime effect; only a validator makes the union true
const unsafeParse = (raw: string): DomainEvent => JSON.parse(raw) as DomainEvent;Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(1) append
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Event Sourcing?
The runtime is JavaScript's, so the stdlib contribution is the type layer: a discriminated union of readonly object types keyed on a literal type field, Extract<DomainEvent, {type:"deposited"}> to name one variant, satisfies (TS 4.9+) to check an upcast table without widening it, and branded types like string & {readonly __id: unique symbol} to stop a StreamId being passed where a version goes. None of that exists at runtime, so the deserialisation boundary needs a real validator; zod's z.discriminatedUnion("type", [...]) is the ecosystem default because its inferred type is exactly the union you already declared.
What is the most common TypeScript mistake when implementing Event Sourcing?
Types erase completely, so the annotation on a deserialised event is a claim, not a check. JSON.parse(raw) as DomainEvent means a 2019 payload whose branch was deleted flows straight into the fold, and the assertNever default arm the compiler proved unreachable is exactly the line that runs in production. The subtler version is optionality: widening an event to amount?: number compiles everywhere, every historical event has undefined, and total += e.amount! makes the balance NaN rather than throwing, so the failure surfaces days later in a report. A type is a promise about code you compile, never about bytes you read.
How does Event Sourcing actually perform in TypeScript?
Erasure means zero runtime overhead: performance is byte-for-byte JavaScript's, so the V8 hidden-class and GC notes apply unchanged. The cost lands on the compiler instead. Non-const enums emit a real object plus a reverse-mapping lookup at runtime, whereas string literal unions compile to nothing, so prefer them for tags. A union of a hundred-plus event variants makes tsc and the editor language service re-check every fold on each keystroke; keeping variants as flat interfaces rather than deep intersections keeps that checking cached and fast. Time complexity is O(1) append and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.