[Typescript] Restrict available operations on values using value objects

Value Objects are another pattern in Domain-driven Design that provide more structure around what you can and cannot do with a type.

In TypeScript we create Value Objects with classes that will define what operations can be performed to the value on the class itself. In this lesson we'll explore how to create a Value Object for our Money type.

 

declare const __brand_type__: unique symbol
type Branded<BrandType, BrandName> = BrandType & {
  readonly [__brand_type__]: BrandName
}
type Currency = "USD" | "EUR"
type Money = Branded<number, "MONEY">

class Money {
  constructor(
    private amount: Money,
    private currency: Currency
  ) {}
    
  add(another: Money) {
    if (this.currency != another.currency) {
      throw new Error(`Cannot add different currencies`);
    }
    return new Money(
      this.amount + another.amount,
      this.currency
    );
  }

  multiply(factor: number) {
    return new Money(this.amount * factor, this.currency);
  }
}

 

Due to definitly assign problem for constructor, you cannot restrict object creation by using constructor. One way to do it is using static from method.

  1. change constructorto private
  2. add static frommethod
declare const __brand_type__: unique symbol
type Currency = "USD" | "EUR"

class Money {
  private constructor(
    private amount: number,
    private currency: Currency
  ) {}
    
  static from(amount: number, currency: Currency) {
    if (amount <= 0) {
      throw new Error(`Cannot add different currencies`)
    }
    return new Money(
      this.amount + another.amount,
      this.currency
    )
  }
    
  add(another: Money) {
    if (this.currency != another.currency) {
      throw new Error(`Cannot add different currencies`);
    }
    return new Money(
      this.amount + another.amount,
      this.currency
    );
  }

  multiply(factor: number) {
    return new Money(this.amount * factor, this.currency);
  }
}

 

posted @   Zhentiw  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-07-29 [SAA + SAP] 12. EC2 Stroage (EBS + EFS)
2020-07-29 [XState] Delay Transitions
2020-07-29 [XState] Transient transitions
2020-07-29 [CSS 3] Add a Cutout Notch to an HTML Element with a CSS Polygon Clip-Path
2020-07-29 [CSS 3] Create an Animated Underline Effect using CSS Transition and CSS Background Position
2018-07-29 [Dart] Understand Variables and Constants in Dart
2018-07-29 [React Native] Prevent the On-screen Keyboard from Covering up Text Inputs
点击右上角即可分享
微信分享提示