Typescript makes Javascript more beautiful (my experience)

Jake Kwon
Jake Kwon
Jul 26, 2017 · 2 min read

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!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade