Domain modeling — aggregates, invariants & services
Model aggregates like Cart with branded IDs and enforce invariants via factories and services.
Domain modeling — aggregates, invariants & services is a free TypeScript Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Intro
Goal: Model a Cart aggregate using branded IDs and ensure rules like qty > 0 are enforced in factories and services.
- Branded IDs distinguish entity boundaries
- Factories return Result unions
- Service functions avoid invalid transitions
Entities & brands
Branded IDs make CartId and ProductId incompatible even though both are strings. This prevents mixups.
type Brand<Tag extends string, T> = T & { readonly __brand: Tag }
type CartId = Brand<"CartId", string>
type ProductId = Brand<"ProductId", string>
type Result<T> = { ok: true; value: T } | { ok: false; error: string }
const cartId = (s: string): CartId => s as CartId
const productId = (s: string): ProductId => s as ProductIdAggregate & invariant
Factories validate rules: qty must be > 0. Only valid Line objects can be created.
type Money = number & { readonly __brand: "Money" }
const money = (n: number): Money => n as Money
interface Line { productId: ProductId; qty: number; price: Money }
interface Cart { id: CartId; lines: Line[]; total: Money }
function makeLine(productId: ProductId, qty: number, price: Money): Result<Line> {
if (!Number.isInteger(qty) || qty <= 0) return { ok: false, error: "qty must be > 0" }
return { ok: true, value: { productId, qty, price } }
}
function makeCart(id: CartId): Cart { return { id, lines: [], total: money(0) } }Service: add item
Service functions perform safe transitions and recalc totals. If totals are invalid, the function returns an error instead of corrupting the state.
function addItem(cart: Cart, line: Line): Result<Cart> {
const lines = [...cart.lines, line]
const totalNum = lines.reduce((s, x) => s + (x.qty * (x.price as number)), 0)
if (!Number.isFinite(totalNum) || totalNum < 0) return { ok: false, error: "invalid total" }
return { ok: true, value: { ...cart, lines, total: (totalNum as unknown) as Money } }
}
// Usage
const c0 = makeCart(cartId("c1"))
const l = makeLine(productId("p1"), 2, money(10))
const c1 = l.ok ? addItem(c0, l.value) : { ok: false, error: "bad line" }Boundary mapping
At boundaries (e.g., APIs), convert to DTOs and validate when parsing back. Factories ensure data is correct.
type CartDTO = { id: string; lines: { productId: string; qty: number; price: number }[]; total: number }
function serialize(c: Cart): CartDTO {
return {
id: c.id as unknown as string,
lines: c.lines.map(x => ({ productId: x.productId as unknown as string, qty: x.qty, price: x.price as unknown as number })),
total: c.total as unknown as number
}
}
function parse(dto: CartDTO): Result<Cart> {
const id = cartId(dto.id)
const lines: Line[] = []
for (const raw of dto.lines) {
const l = makeLine(productId(raw.productId), raw.qty, money(raw.price))
if (!l.ok) return { ok: false, error: l.error }
lines.push(l.value)
}
const totalNum = lines.reduce((s, x) => s + (x.qty * (x.price as number)), 0)
return { ok: true, value: { id, lines, total: money(totalNum) } }
}Tips
Best practices:
- Centralize validation in factories.
- Keep service functions pure and deterministic.
- Do brand conversions only at system boundaries.
Invariant check
Quick check: How should you enforce an invariant like qty > 0?
Recap
Recap: Branded IDs combined with factories and services enforce invariants. Invalid states cannot be created because all entry points validate input.
Frequently asked questions
Is the “Domain modeling — aggregates, invariants & services” lesson free?
Yes — the full text of “Domain modeling — aggregates, invariants & services” is free to read here on the web, and the TypeScript Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Domain modeling — aggregates, invariants & services”?
Model aggregates like Cart with branded IDs and enforce invariants via factories and services. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start TypeScript Academy?
No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “Domain modeling — aggregates, invariants & services” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this TypeScript Academy lesson?
Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Branding/opaque types to prevent unit mixups
- Tagged IDs and domain modeling patterns
- Domain modeling — aggregates, invariants & services