Last active
August 12, 2022 07:30
-
-
Save harajune/9719e028e1af749c6163b162c19d471a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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