Intro to Typescript for Javascript devs

Intro to Typescript for Javascript devs

If you're a JavaScript developer, you might have already heard of TypeScript. According to its official docs it says:

"TypeScript is an open-source language that builds on JavaScript, one of the world’s most used tools, by adding static type definitions."

So essentially, it’s just JavaScript with static typing.

But, What's Static Typing?

Programming languages can be either of two types i.e. statically typed or dynamically typed.

In languages with static typing, the type of the variable must be known at compile-time. If we declare a variable, it should be known by the compiler if it will be a number, a string, or a boolean.
For example: Java and C.

In languages with dynamic typing, the type of a variable is known only when running the program.
For example: Python and Javascript.

Static typing: Types checked before run-time.
Dynamic-typing: Type checked at run time.
Let's look at an example & try to undertsand this!

const add = (value) => {
    return value * 5;
}
let sum = add('10');
// output: 50

Can you spot the bugs here..??
It's a common silly mistake that we are passing a string to add rather than a number. But even than javascript implicitly converts the string to a number & then adds it. But what if we pass an actual string over here..

let sum2 = add('abc');
// output: NaN

As you can see it returned us NaN which is Not a Number

So, to avoid such common runtime errors typescript is widely used among javascript developers as typescript catches these mistakes before they reach runtime, and instead, are caught at compile time.

Why should I use Typescript??

  • As you can see implementing typescript on our project saves a lot of time in the long run.

  • TypeScript always point out the compilation errors at the time of development only. Because of this at run-time the chance of getting errors are very less as compared to javascript

  • Refactoring becomes very easy because if you make a change in your code typescript will throw you an error everywhere that particular block of code is written and then you would know where you have to exactly make the other changes.

  • As your app grows and you add more features, typescript will help you while you are writing more features and there is a chance that you might break something unknowingly so it acts as a first layer of static typing as it will gives you enough information if you are breaking something on atleast the type layer.

So, now as we understood what is typescript & why should we use typescript.
Let's dive into it & understand how can we use typescript in our react apps.

Using Types with Typescript

Basic Types

Typescript has a number of basic types that are pre-defined.
For eg: Number, string, boolean, etc

let num: number = 12;
let name: string = "prerana";
let isCorrect: boolean = true;

Capture.PNG

So, as you can see typescript quickly gives an error that we can't assign number type to a string variable.

For Arrays

// Two ways to define arrays with types
const strings: string[] = ['Hello', 'Hii', 'Ok'];
let names: Array<string> = ['Prerana', 'Siddhi', 'Ritu'];

image.png

As names array is an array of string if you try to add any other element with another data type typescript will give us an error.

For Objects

type Person = {
    gender: string;
    age: number;
    isSingle: boolean;
}

const siddhi: Person = {
    gender: 'female',
    age: 17,
    isSingle: false
}

image.png

If you see here, typescript gives us an error with detailed description that we can't directly add another property without declaring it in type.

For any type

any type represents all possible javascript values i.e. primitives, objects, arrays, functions, errors, symbols, etc.
So in typescript, every type is assignable to any. This makes any a top type (also known as a universal supertype) of the type system.

let newVar: any = 'Hello World';
newVar = 89;
newVar = false;

Union Type

Union types are a powerful way to express a value that can be one of the several types. Two or more data types are combined using the pipe symbol |.

let numOrBool : number | boolean = 20;
numOrBool = true;
numOrBool = "wrong"; // error

Custom types

Using an interface

interface Address {
    house: string,
    streetNo: number,
    street: string,
    city: string,
}

const address1: Address = {
    house: 'Abhinav Society',
    streetNo: 12,
    street: "M. G. Road",
    city: "Mumbai",
}

Using a type

type Address = {
    house: string;
    streetNo: number;
    street: string;
    city: string;
}

const address1: Address = {
    house: 'Abhinav Society',
    streetNo: 12,
    street: "M. G. Road",
    city: "Mumbai",
}

Difference between type & interface

The term "type" in here is referring to the"type" aliases in typescript

So, in general programming, interfaces are used to define data structures & types are used to define the type of data.
Most of the time types & interfaces are used interchangeably in typescript. Many developers don't really know the real difference between these two. Having known the differences, we can implement these according to the best use case for us.

1. Declaration Merging

One of the key differences between the two is that interfaces can be 'mutated' while we cannot mutate types.
While with interfaces we are allowed to add new fields to the interface, which means that we are mutating the object type. Also, this does not create two different declarations, nor does it override the original declaration, but rather merges them.

  interface Person {
    name: string;
  }

  interface Person {
    age: number;
  }

  const siddhi: Person = {
    name: "Siddhi",
    age: 17
  };

But with types when trying to merge two declarations, we will get an error.

image.png

2. Union

We can combine multiple types and interfaces with the union keyword | into a single type. But, we cannot combine them into a single interface.

  type Red = {
    name: string;
  };

  type Black = {
    name: string;
  };

  type colors = Red | Black; // valid
  interface Red  {
    name: string
  };

  interface Black  {
    name: string
  };

  interface colors = Red | Black; // invalid
  type colors = Red | Black; // valid

3. Intersection

We can combine multiple types and interface with the& keyword into a single type. But, we cannot combine them into a single interface.

  type Red = {
    name: string;
  };

  type Black = {
    name: string;
  };

  type colors = Red & Black; // valid
  interface Red  {
    name: string
  };

  interface Black  {
    name: string
  };

  interface colors = Red & Black; // invalid
  type colors = Red & Black; // valid

Function parameter types and return types

Similar to variable types, you can define types for function parameters and return values. While the parameter type is declared next to the parameter name, return type is declared just before the curly braces.

  type Cart = {
    name: string;
    price: number;
  };

  const pen: Cart = {
    name: "Pen",
    price: 17
  };
  const paper: Cart = {
    name: "Paper",
    price: 18
  };
  const pencil: Cart = {
    name: "Pencil",
    price: 19
  };

  const productsInCart: Array<Cart> = [pen, paper, pencil];

  function getTotalPrice(products: Array<Cart>): number {
    return products.reduce((acc, prod) => acc + prod.price, 0);
  }

  const totalPrice = getTotalPrice(productsInCart);
  console.log(totalPrice); // 54

Conclusion

In my opinion Typescript will give you a lot helpful features on top of Javascript and no disadvantages at all.

But it depends on every person as some of you may like and enjoy the freedom of Javascript and dont want to bound to type and such things. And thats okay! But for me and may others out there Typescript really helps to organize the code better & gives various benefits.

Let me know what you think about this article, and programming in general, through my Twitter and LinkedIn handles. I would love to connect with you out there!

More articles coming soon! :) Peace!

Did you find this article valuable?

Support Prerana Nawar by becoming a sponsor. Any amount is appreciated!