Skip to content

Instantly share code, notes, and snippets.

@harajune
Last active August 12, 2022 07:30
Show Gist options
  • Select an option

  • Save harajune/9719e028e1af749c6163b162c19d471a to your computer and use it in GitHub Desktop.

Select an option

Save harajune/9719e028e1af749c6163b162c19d471a to your computer and use it in GitHub Desktop.
enum MoneyType {
Dollar,
Yen
}
class Money {
constructor(
private readonly _value: number,
private readonly _type: MoneyType
) {}
equals(other: Money) {
this._raiseIfTypeIsDifferent(other)
return this._value === other._value
}
add(other: Money) {
this._raiseIfTypeIsDifferent(other)
return new Money(
this._value + other._value,
this._type
)
}
private _raiseIfTypeIsDifferent(other: Money) {
if (this._type !== other._type) {
throw Error("Invalid type of Money")
}
}
}
// Value Object
const dollar = new Money(100, MoneyType.Dollar)
const yen = new Money(100, MoneyType.Yen)
// ランタイムエラーになる
dollar.add(yen)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment