CQRS Pattern 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
- ✓CQRS Pattern runs in O(1) time and O(n) space, in TypeScript as in every other language.
- ✓Nothing at run time, but this is the language where the pattern gains the most from types.
- ✓Define one union of command types keyed by a literal kind, define a separate map type from kind to result, and make dispatch generic over the union so the return type is looked up rather than widened.
- ✓The TypeScript trap: The common shape is a bus typed as dispatch(command: Command): Promise<unknown>, which discards the entire benefit and pushes a cast to every call site, where it is invisible and unchecked.
- ✓All of it is erased, so the generated code is the JavaScript version. The mapped and conditional types add compile time, which on a union of a few dozen commands is negligible.
What CQRS Pattern actually is
CQRS Pattern in TypeScript: what you actually reach for
TypeScript implementation
type Command =
| { readonly kind: 'CreateOrder'; readonly orderId: string; readonly items: readonly string[] }
| { readonly kind: 'CancelOrder'; readonly orderId: string; readonly reason: string }
| { readonly kind: 'ShipOrder'; readonly orderId: string; readonly carrier: string };
// The result each command produces, keyed by the same discriminant.
interface ResultMap {
CreateOrder: { orderId: string; createdAt: string };
CancelOrder: void;
ShipOrder: { trackingNumber: string };
}
type HandlerFor<K extends Command['kind']> = (
command: Extract<Command, { kind: K }>,
) => Promise<ResultMap[K]>;
type Registry = { [K in Command['kind']]: HandlerFor<K> };
const registry: Registry = {
CreateOrder: async (cmd) => ({ orderId: cmd.orderId, createdAt: new Date().toISOString() }),
CancelOrder: async (_cmd) => undefined,
ShipOrder: async (_cmd) => ({ trackingNumber: 'TRK-1' }),
};
// Adding a variant to Command WITHOUT adding it here is a compile error:
// the mapped type requires a key for every member of the union.
/**
* Generic over the union, so the return type is LOOKED UP per command.
* The common mistake is "dispatch(c: Command): Promise<unknown>", which
* throws all of this away and forces a cast at every call site.
*/
export async function dispatch<K extends Command['kind']>(
command: Extract<Command, { kind: K }>,
): Promise<ResultMap[K]> {
const handler = registry[command.kind] as HandlerFor<K>;
return handler(command);
}
// const r = await dispatch({ kind: 'ShipOrder', orderId: 'o1', carrier: 'ups' });
// r.trackingNumber <- typed string, no cast anywhereThink 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)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for CQRS Pattern?
Nothing at run time, but this is the language where the pattern gains the most from types. A discriminated union of commands plus a mapped type from each command kind to its result gives a bus that returns the right type per command with no cast at the call site.
What is the most common TypeScript mistake when implementing CQRS Pattern?
The common shape is a bus typed as dispatch(command: Command): Promise<unknown>, which discards the entire benefit and pushes a cast to every call site, where it is invisible and unchecked. The generic lookup version costs a few lines once and removes every cast. The second thing to be clear about is readonly: it is a compile-time annotation that is erased, so it prevents your own code from assigning and does nothing at run time. A readonly command handed to a library, or reached through an any, is mutable like any other object. If immutability has to hold at run time, freeze it as well as typing it.
How does CQRS Pattern actually perform in TypeScript?
All of it is erased, so the generated code is the JavaScript version. The mapped and conditional types add compile time, which on a union of a few dozen commands is negligible. Time complexity is O(1) 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 trialIf you are a student, see what GitHub Copilot offers students for free 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.