Typescript makes Javascript more beautiful (my experience)

Recently I have been playing around with Angular 2 and discovered that it uses Typescript as opposed to plain Javascript.

So before I jumped into Angular 2 I decided to play around with Typescript and discovered the many advantages of it. As a programmer with a strong OOP background it turns out that Typescript can be quite similar to C++, Java; there is support for private/public, static variables, classes, encapsulation, data types, generics, as well as the newest featuers of ES6/7

Here is an example of a OOP approach to Typescript (you can copy paste it and play around with it at http://www.typescriptlang.org/play/ )

class Person { 
static totalPersonCreated: number = 0;
constructor(private name: string, private age: number) { 
Person.totalPersonCreated++;
}
getName():string {
return this.name;
}
getAge():number {
return this.age;
}
}
class Employee extends Person { 
constructor(name:string, age:number, private isFullTime:boolean, private empId:number) {
super(name, age);
}
getInfo():string {
return super.getName() + " " + super.getAge() + " " +
this.empId + " " + (this.isFullTime ? "FT" : "PT");
}
getId():number {
return this.empId;
}
isEmployeeFullTime(): boolean{
return this.isFullTime;
}
}
class Payroll { 
employees: Employee[] = [];
addEmployee( employee:Employee) { 
if (employee) {
this.employees.push( employee );
}
}
getEmployeeAt(index:number):Employee {
if (this.employeeExists(index)){
return this.employees[index];
}
return null;
}
removeEmployeeAt(index:number):Employee {
if (this.employeeExists(index)){
return this.employees.splice(index, 1)[0];
}
return null;
}
private employeeExists(index:number):boolean {
return (index >= 0 && index < this.employees.length);
}
getSize():number {
return this.employees.length;
}
}
var payroll = new Payroll();
payroll.addEmployee( new Employee("Jake", 26, true, 1001));
payroll.addEmployee(new Employee("Anna", 33, false, 1002));
for (let i = 0; i < payroll.getSize(); i++){ 
let emp = payroll.getEmployeeAt(i);
console.log(emp.getInfo());
}
var removedEmp = payroll.removeEmployeeAt(1);
console.log( removedEmp.getName() + " " + removedEmp.getId() + " has been removed from payroll." );
console.log("Remaining employees = " + payroll.getSize());
console.log("Total persons created = " + Person.totalPersonCreated);

Enjoy!

Like what you read? Give Jake Kwon a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.