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;}}Report a problem with this exampleOpens a pre-filled issue on GitHub.