Back to articles
Algebraic Data Types in TS: Indestructible Payment Flows

Algebraic Data Types in TS: Indestructible Payment Flows

via Dev.toHugo Campañoli

Your payment flow has a status: string field? You're one typo away from a double charge. A silent "pednign" in production won't throw an error; it loses money. Algebraic Data Types (ADTs) in TypeScript let you model states where invalid data is compiler-illegal. Not just "unlikely." Forbidden. The problem: The bag of optionals // ❌ Everything is possible... including double charging interface PaymentState { status : string ; transactionId ?: string ; errorMessage ?: string ; receiptUrl ?: string ; retryable ?: boolean ; } // When does transactionId exist? // Is it safe to read receiptUrl? // Nobody knows. Runtime will tell. When you use a simple string for status, you end up with an interface where everything is optional. The compiler cannot help you because it doesn't know the relationship between the status and the data. The solution: Discriminated Unions // ✅ The compiler forbids illegal states type PaymentState = | { status : " idle " } | { status : " pending " ; intentId : string

Continue reading on Dev.to

Opens in a new tab

Read Full Article
0 views

Related Articles