Skip to content

Instantly share code, notes, and snippets.

@harajune
Created August 15, 2022 06:05
Show Gist options
  • Select an option

  • Save harajune/37adafa9a31094fc18e22d51d792a2ab to your computer and use it in GitHub Desktop.

Select an option

Save harajune/37adafa9a31094fc18e22d51d792a2ab to your computer and use it in GitHub Desktop.
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