Skip to content

Instantly share code, notes, and snippets.

@isaacbatst
Created April 5, 2022 22:27
Show Gist options
  • Save isaacbatst/8648a4990e5d39c0e0b2dcec41431c7b to your computer and use it in GitHub Desktop.
Save isaacbatst/8648a4990e5d39c0e0b2dcec41431c7b to your computer and use it in GitHub Desktop.
export default class Person {
constructor(
protected readonly _name: string,
protected _birthDate: Date
) {
}
private calcAge(){
const timeDiff = Math.abs(Date.now() - new Date(this._birthDate).getTime());
return Number((timeDiff / (1000 * 3600 * 24) / 365.25).toFixed(1));
}
get age(){
return this.calcAge()
}
// ou
public getAge(): number {
return this.calcAge();
}
set birthDate(date: Date) {
this._birthDate = date;
}
}
const person = new Person('Isaac', new Date('06/02/1998'))
// person.age = 1; // Não é possível atribuir a 'age' porque é uma propriedade de somente leitura.
console.log(person.age); //23.8
person.birthDate = new Date('06/02/2005');
console.log(person.age) //16.8
console.log(person.getAge()) //16.8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment