Skip to content

Instantly share code, notes, and snippets.

@A-Maged
Last active February 16, 2022 17:15
Show Gist options
  • Save A-Maged/6613c41e3141856168eba92862316a2a to your computer and use it in GitHub Desktop.
Save A-Maged/6613c41e3141856168eba92862316a2a to your computer and use it in GitHub Desktop.
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