Five big improvements that TypeScript bring over ES5:
TS is more popular than ever, due to its usability in latest Angular development. There are lots of reasons to use TS over ES5, here I list some of the important key features.
- Types
- Classes
- Decorators
- imports / Export
- Language utilities.
Types
The major improvement over ES5 in TS is typing system. Typeig system gives the language its name. Most of the developers consider that lack of type checking in ES5 as an advantage. But let’s give it a try.
Advantages of using Types.
- Avoid compile time errors
- Increase Code readability and make clear to others about your intention.
The syntax of declaring variable name implies from the ES5 but here you optionally provide the data type along with the variable name.
ES5:
var variableName;
TS :
var variableName : srting;
var variableName : number;
var functionName ( args1 : string , args2 : number,args3 : boolean) : boolean{ return true; }
TS Error:
var functionName ( args1 : string , args2 : number,args3 : boolean) : boolean{
return 12;
}
This code block return compiler error as function expecting boolean but it returning number.
Using types will sure save us from lots of bugs. Let’s dig deeper on available built-in types.
Available Built-in Types
- string
- number
- boolean
- array
As array is a collection of object we need to mention the type objects
var variableName : Array<string> = ['icodefy','imacify','igamefy'];
var variableName : string[] = ['icodefy','imacify','igamefy'];
Similar with numbers.
- Enums
- Void – return nothing
- Any – Default type. You can omit this
Classes
ES5 OOP’s is accomplished by using the prototype based object. These models rely on prototypes instead of classes. After compensating the lack of classes. Finally, ES6 has its own built-in classes.
To define the class you have to use “class” key word along with its class name. The class may have properties, methods, and constructors.
class class_name {
....
}
Property – defines the data attached to an instance of the class.
class car {
name:string;
seating : number;
fuelType : string;
}
Methods – Function that runs in the context of the class.
To call a method inside the class we first need to create a new instance of that class object using “new” keyword
class car {
name:string;
seating : number;
fuelType : string;
}
getCarName(){
return this.name;
}
If you have a look into that function we must access the name using the “this” keyword.
When methods do not declare any type then it assumes as “Any“. If the method is not returning any value then you need to specify the type as “void“.
As I above mention if you want to access the getCarName method you need an instance of the class object.
//Declare the object type
var c = car;
//Create new instance for car
c = new car();
//Assign data to created new instance c
c.name = "BMW X1";
c.seating = 4;
c.fuelType = "petrol";
//calling the method
console.log(c.getCarName());
Notice , you can declare the variable and instance it in a single line also
var c : car = new car();
Constructors – Special method executed when a new instance of the class is calling.
If the class doesn’t have explicitly declared constructor then it will generate by its own.
class car{
}
var c : car = new car()
Is same as
class car{
constructor(){
}
}
var c : car = new car();
Constructors can take parameters which help of passing the value at the time of new instance creation.
class car {
name:string;
seating : number;
fuelType : string;
}
//Constructor Parameters
constructor(name:string, seating:number,fuelType:string){
this.name = name;
this.seating : seating;
this.fuelType:fuelType;
}
getCarName(){
return this.name;
}
Finally, the constructor makes our new class declaration bit simpler. Refer the current code with the previous example of creating the class and assign the value.
var c :car = new car('BMW X1',4,'petrol')
Inheritance
Inheritance is one of the important features of OOP’s. It refers to the property inherited by the child from its parent class. TS completely support inheritance which is achieved through “extends” keyword. Then we can modify and override inherited property.
class car {
name:string;
seating : number;
fuelType : string;
}
getCarName(){
return this.name;
}
In below snippet, we are overriding the getCarName function.
class luxuryCar extends car {
name:string;
seating : number;
fuelType : string;
getCarName(){
return "Name : " + this.name ;
}
}
var c :luxuryCar = new luxuryCar('BMW X1',4,'petrol')
console.log(c.getCarname());
//Result - Name : BMW X1
Language Utilities
Fast Arrow Function
Fast arrow function is the shorthand notation of writing functions.
ES5:
var carName = ["Volvo v90", "BMW x1"]
carName.forEach(function(name){
console.log(name)
});
the same can be rewritten in TS as shown below
TS:
var carName = ["Volvo v90", "BMW x1"]
carName.forEach( (name) => console.log(name)) ;
Paranthesis are optional if function have single statement
Arrow functions clean up the inline function and make it even easier while using high order functions.
Template Strings
Template string is the most powerful feature included in ES6. Using this you can add variable and HTML tags to the string. Template string is quoted inside the back tick “`”. Along with the variable usage in template string, you can also include multi line strings.
var carName = 'Volvo v90';
var templateString = ` <div>
<h2> Featured Cars</h2>
<p> New Arival ${carName} </p>
</div>`;
Decorators
The decorator is a special kind of additional property attached to a class, method or a property. We use decorators with syntax “@expression“. Where expression is the function that called at the time of runtime with information about the decorator.
function func1() {
console.log("func1(): evaluated");
return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("func1(): called");
}
}
function func2() {
console.log("func2(): evaluated");
return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("func2(): called");
}
}
class Car {
@func2()
@func2()
method() {}
}
Import & Export
The relationships between modules are specified in terms of imports and exports at the file level. This helps to Import and export the declarations between the modules.Modules import one another using a module loader. At runtime, the module loader is responsible for locating and executing all dependencies of a module before executing it.
export class SearchRankComponent implements OnInit {
@Input() search : searchRank;
constructor() {
}
ngOnInit() {
}
upVote():boolean{
this.search.upVote();
return false;
}
downVote():boolean{
this.search.downVote();
return false;
}
import { things } from wherever
import { enableProdMode } from '@angular/core';
Destructuring
Name derived from the word de-structuring, which means breaking up of structures.
var obj = { x: 0, y: 10, width: 15, height: 20 };
// Destructuring assignment
var {x, y, width, height} = obj;
console.log(x, y, width, height); // 0,10,15,20
obj.x = 10;
({x, y, width, height} = obj); // assign to existing variables using outer parentheses
console.log(x, y, width, height); // 10,10,15,20
If destructuring is not there we have to pick off the values one by one in obj.
And that’s it! You are ready with the basic understanding of typescript and ES6 features.