Value Object Immutable Compare

Create immutable value objects with structural equality and validation for domain-driven design.

TypescriptData Integrity

Code

typescriptsnippet
1 line
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<0 short-circuits the flow with an early throw when 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

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.