What is Typescript and why should I learn it ?

What is Typescript and why should I learn it ?

confusion 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 new-ts.png

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:

  1. Type Aliases
    type Square = { 
       area: number,
       perimeter: number
    }
    
  2. Interface
    interface Square { 
       area: number,
       perimeter: number
    }
    
    I'll discuss the difference between the two in my next blog!

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! happy