
Meaningful Domain Models in TypeScript
Most bugs I've seen in production weren't caused by wrong algorithms or bad infrastructure. They were caused by invalid state — an order with no items, a paid order without an invoice ID, a payment that spent more than expected. The code was syntactically correct. TypeScript was happy. But the business rules were silently violated. This post explores a few patterns that help you build domain models that make invalid states impossible — and when something does go wrong, make failures explicit . The problem with implicit rules Consider a typical order entity: class Order { status : " DRAFT " | " PLACED " | " PAID " ; items : OrderItem []; invoiceId ?: string ; } Nothing stops you from creating a PAID order with no invoiceId . Nothing stops you from removing the last item. The rules exist in your head (or a comment somewhere), not in the code. You might add validation in one place — a use case, a controller — but nothing prevents another developer (or future you) from mutating state from
Continue reading on Dev.to Webdev
Opens in a new tab




