Created
August 15, 2022 06:05
-
-
Save harajune/37adafa9a31094fc18e22d51d792a2ab 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
| class Money<T extends Money<T>> { | |
| constructor( | |
| private readonly _value: number | |
| ) { | |
| } | |
| equals(other: T) { | |
| return this._value === other._value | |
| } | |
| add(other: T): T{ | |
| return Money.create<T>(this._value + other._value) as T | |
| } | |
| static create<U extends Money<U>>(value: number) { | |
| return new Money<U>(value) as U | |
| } | |
| } | |
| type Dollar = Money<Dollar> & { _dollar: never } | |
| type Yen = Money<Yen> & { _yen: never } | |
| // Value Object | |
| const dollar = Money.create<Dollar>(123) | |
| const yen = Money.create<Yen>(123) | |
| // ok | |
| console.log(dollar.equals(dollar)) | |
| console.log(dollar.add(dollar)) | |
| // 型エラー | |
| dollar.equals(yen) | |
| dollar.add(yen) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment