[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.
- change
constructor
toprivate
- add
static from
method
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);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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