Skip to content

Instantly share code, notes, and snippets.

@leonardofreitass
Last active August 2, 2017 20:04
Show Gist options
  • Save leonardofreitass/df89a59482bd7e7e1ff154ae447b0b39 to your computer and use it in GitHub Desktop.
Save leonardofreitass/df89a59482bd7e7e1ff154ae447b0b39 to your computer and use it in GitHub Desktop.
Person class wrote in TypeScript
class Person {
private name: string;
private age: number;
constructor(name: string, age: number){
this.name = name;
this.age = age;
}
advanceAge(){
this.age++;
}
getAge(){
return this.age;
}
passALotOftime(years: number){
this.age += years;
}
}
function doBirthday(citizen: Person){
citizen.advanceAge();
console.log(`Happy ${citize.getAge()} years!`);
}
const leonardo = new Person('Leonardo', 21); // As you can see, I don't have to explicity declare the type, because TS knows that is the Person type
doBirthday(leonardo);
leonardo.age = 21; // Note that this is not possible, because age is a private attribute
leonardo.passALotOftime('twenty'); // Neither is this, because this method expects a number, not a string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment