Yes, I got this question thousands of times that when we have JavaScript, why should I learn another language. I am sure you guys too have the same question. Finally, I got the answer! So this blog aims to answer the same.
Excited, Let's Start!
Okay, so first thing first
What is Typescript?
- Typescript is a programming language (Types + JavaScript)
- Superset of JavaScript
Disclaimer is in the browser we can run only JavaScript. So Typescript compiler completes checking of code and then erases all types and produces JavaScript complied code!
Now, the Question arises …
What are Types?
- Types, in layman means adding rules about how different kinds of values can be used.
const myName: string = "Payal Kherajani" ; //type is string
const age: number = 23; //type is number
const eligibleForVote: boolean = true; //type is boolean
So it defines that type of myName variable is a string and same for others and it would give you type error if any other type of value you provided!
Note: Defining explicitly the type of the variable, is known as Type Annotations
Other examples are
const arr: number[] = [ 1, 2, 3] //arr variable is a array of numbers only
How to write Types?
There are 2 ways:
- Type Aliases
type Square = { area: number, perimeter: number }
- Interface
I'll discuss the difference between the two in my next blog!interface Square { area: number, perimeter: number }
Why Should I learn Typescript?
- Static Type Checker: Yes, typescript has a static type checker which means that it will detect errors in the code based on the kind of values it is being operated on. i.e checks a program for errors before execution
const obj = { width: 10, height: 15 };
const area = obj.width * obj.heigth;
Property 'heigth' does not exist on type '{ width: number; height: number; }'. Did you mean 'height'?
Inference: Provide type information when there is no explicit type annotation.
let x = 3 It will tell, let x: number when you hover over it.
Less Prone to Errors!
It Easier to debug the code!
Makes refactoring of code much easy and fast!
We are done! 🥳 Hope you guys enjoyed it!