Last active
August 2, 2017 20:04
-
-
Save leonardofreitass/df89a59482bd7e7e1ff154ae447b0b39 to your computer and use it in GitHub Desktop.
Person class wrote in TypeScript
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 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