Value Object Immutable Compare
Create immutable value objects with structural equality and validation for domain-driven design.
Code
export abstract class ValueObject{abstract equals(other:ValueObject):boolean;abstract toString():string;}export class Money extends ValueObject{constructor(readonly amount:number,readonly currency:string){super();if(amount<0)throw new Error('negative money');if(!/^[A-Z]{3}$/.test(currency))throw new Error('invalid currency');}add(other:Money):Money{if(this.currency!==other.currency)throw new Error('currency mismatch');return new Money(this.amount+other.amount,this.currency);}equals(other:ValueObject):boolean{return other instanceof Money&&this.amount===other.amount&&this.currency===other.currency;}toString():string{return this.amount.toFixed(2)+' '+this.currency;}}How the snippet works
The working surface is the classes ValueObject and Money — everything else is wiring.
Error is the guard’s signal — thrown at the branch, before any partial work happens.
What comes back is a new object, not a reference to anything passed in.
What to watch for
- The guard
amount<0short-circuits the flow with an earlythrowwhen its condition holds.
Using it
The surface worth importing is Money; the helpers around it are private to the snippet.
Interactive Tools for This Topic
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text Diff ComparisonCompare two text blocks line by line and visualize the differences with added, removed, and unchanged lines highlighted. Useful for reviewing changes and patches.
FAQ
- Does `Money` modify its input?
- No. Nothing passed in is written to, which makes the call safe on shared data.
- How are precondition violations signaled?
- The code refuses to continue: `Error` is thrown while the state is still recoverable.
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement.
Report a problem with this exampleOpens a pre-filled issue on GitHub.