Introduction to TypeScript
Hands-On Introduction on TypeScript
TypeScript is not a new language. It is a super sort of JS with some additional features.
- Any valid JS code is valid TS code.
Reason behind TypeScript
- Strong Typing: Like any other language as Java, C# there is not compulsion for typing a variable in TS. But typing makes our application predictable and more easier to debug.
- Object oriented features.
- Compile time errors (not all sort of errors)
Note: Typescript file gets transpile into JS so that browser can understand them. But we don’t need to transpile them manually as Angular CLI does this work under the hood by itself.
Declaring Variables
- We declare it using let and var keyword. let keyword did not arrive before ES6 and all the browser works on ES5 which only works for var keyword.
- So even if we will make function having let keyword as in the TS file then automatically it will get converted into var keyword in transpiled JS file.
- The keywords
let
andvar
both declare new variables in JavaScript. The difference betweenlet
andvar
is in the scope of the variables they create: - Variables declared by
let
are only available inside the block where they’re defined. - Variables declared by
var
are available throughout the function in which they’re declared.
// Declaring variable of Number Datatype
var count = 1;
let number = 2;
Type Assertion
- Changing the type of given variable.
let message;
message = 'abc';
// right now message is of any type as we haven't declared any to it
let endsWithC = (<string>message).endsWith('c');
let alternativeWay = (message as string).endswith('c');
Arrow Function
- In JS we could have made functions in the below given way
let log = function(message){
console.log(message);
}
- In TS, we can do it much more simply
let doLog = (message) => {
console.log(message);
}
// For the function with only one line
let doLog = (message) => console.log(message);
// For the function with no parameter
let doLog = () => console.log();
Objects
- Here in below given code point is the object of the Point class.
- Object is nothing just an instance of a class.
class Point {
x: number;
y: number;
draw(): void{
console.log('X: ' + this.x + ', Y: ' + this.y);
}
getDistance(another: Point){
//....
}
};
let point = new Point();
point.x = 1;
point.y = 2;
point.draw();
Constructor
- The constructor is a method in a TypeScript class that gets called when the class is being instantiated.
- It’s not an Angular feature but rather a concept that’s present in most Object-Oriented languages including TypeScript.
class Point {
x: number;
y: number;
constructor(x: number, y: number){
this.x = x;
this.y = y;
}
draw(): void{
console.log('X: ' + this.x + ', Y: ' + this.y);
}
};
let point = new Point(1 , 2);
point.draw();
Access Modifiers
- Public: By default all members are public. We don’t need to prefix members with the public keyword. They are accessible everywhere without restrictions.
- Private: A private member cannot be accessed outside of its containing class. Even their subclass won’t be allowed to use them.
- Protected: A protected member cannot be accessed outside of its containing class. It can also be accessed by the instance/subclass of its class.
But if user wants to check the value of coordinate then how will he be able to check it, as we knew that private members are not allowed to be called outside of the class.
class Point {
constructor(private x?: number, private y?: number){
this.x = x;
this.y = y;
}
draw(): void{
console.log('X: ' + this.x + ', Y: ' + this.y);
}
getX() {
return this.x;
}
};
let point = new Point(1 , 2);
let x = point.getX();
point.draw();
- As you saw we can’t access private member outside of the class but we can make method inside of the class and use that method to get access to private members outside of the class.
Now if we want to change the value of the private member then also it’s better to make a method regarding that:
class Point {
constructor(private x?: number, private y?: number){
this.x = x;
this.y = y;
}
draw(): void{
console.log('X: ' + this.x + ', Y: ' + this.y);
}
getX() {
return this.x;
}
setX(value) {
if(value < 0)
throw new Error('value cannot be less than 0')
this.x = value;
}
};
let point = new Point(1 , 2);
let x = point.getX();
point.setX(10);
point.draw();
Module
- In TS each file can be considered as module.
- For making each file module we have to add export keyword before class to make it accessible outside of the file.
- In TS we divide the program into multiple files, in each files we export one or more types
- These types can be classes, functions, simple variables or objects. Wherever we need to use these file we need to import them first.
- When we have an import or export on the top of the file then that file is module in respect to typescript point of view.
- In Angular we also have concept of module but Angular modules are little bit different, they are not about organization of code in different files. They are about organization of application into smaller functional areas.
With all this, let’s end this blog as this is it of Hands on Introduction to TypeScript. If you will find any issue regarding concept or code, you can message me on my Twitter or LinkedIn. The next blog will be published on 05 March 2023.
Some words about me
I’m Mohit.❤️ You can also call me Chessman. I’m a Machine learning Developer and a competitive programmer. Most of my time is spent staring at a computer screen. During the day, I am usually programming, working to derive insight from large datasets. My skills include Data Analysis, Data Visualization, Machine learning, Deep Learning, DevOps and working toward Full Stack. I have developed a strong acumen for problem-solving, and I enjoy occasional challenges.