Last active
February 16, 2022 17:15
-
-
Save A-Maged/6613c41e3141856168eba92862316a2a 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 Adult { | |
age: AdultAge; | |
constructor(age: AdultAge) { | |
this.age = age; | |
} | |
} | |
/* value object */ | |
class AdultAge { | |
/* readonly, so we can't set it and go around validation in constructor */ | |
readonly value: number; | |
constructor(value: number) { | |
/* validation */ | |
if (value < 18) { | |
throw new Error(`invalid age of: ${value}`); | |
} | |
this.value = value; | |
} | |
equals = (otherAdultAge: AdultAge) => { | |
return this.value === otherAdultAge.value; | |
}; | |
} | |
/* | |
const adultAge = new AdultAge(17); // Throws an error, because it must be >= 18 | |
const adult = new Adult(19); // typescript error, must pass AdultAge object | |
*/ | |
const adultAge = new AdultAge(18); // Works | |
const adult = new Adult(adultAge); | |
const adultAge2 = new AdultAge(19); | |
const adult2 = new Adult(adultAge2); | |
console.log(adultAge2.value); | |
console.log(adultAge.equals(adultAge2)); // false | |
console.log(adultAge2.equals(new AdultAge(19))); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment