JavaScript on Steroids: Why and How Pros use TypeScript
Tags: javascript, typescript, webdev, tutorial
Published: 2022-02-06 06:59:53

---
canonical_url: https://tapajyoti-bose.medium.com/javascript-on-steroids-why-and-how-pros-use-typescript-f701fadba5e4---

With the surge in popularity of **TypeScript**, we are witnessing a humongous number of developers ditching **JavaScript** in favor of **TypeScript**. Often junior developers are left scratching their heads over why the shift is taking place and how to make the most of it.

This article will help you nail **TypeScript** and provide insights into why it is better than **JavaScript**.

# Why TypeScript?

Before we start with _Why_, we should probably look at _What is **TypeScript**?_

> TypeScript is a programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. TypeScript is designed for the development of large applications and transcompiles to JavaScript

**TypeScript** adds an additional layer of `static typing`, which helps the developer avoid a lot of _difficult to find bugs_ at _development time_ instead of _runtime_. It also helps a lot in **IntelliSense**, providing precise code completion suggestions, so no more _stumbling around in the dark_.

![stumbling around in the dark](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mpf6r4665mcm546gm5jx.gif)

**TypeScript** is nothing but **JavaScript** with some _additional features_ and can be compiled as per **ES5** and **ES6** standards to _support the latest browser_. When combined with **IDEs** like **VS Code**, it can _save developers hundreds of hours_.

# Getting Started

## Installing TypeScript

Before writing any **TypeScript** code, we need to install the **TypeScript** package first.

```bash
npm install -g typescript
```

Keeping **TypeScript** installed as a global package is a good idea as it will allow **node** to execute **TypeScript** files directly using `node <file.ts>`. But for a project, you should install it as a _local package_ using

```bash
npm install -D typescript
```

## Initializing a TypeScript Project

To initialize a **TypeScript** project, we need to create a `tsconfig.json` file in the _root directory_ of the project. You can auto-generate it using

```bash
tsc --init
```

## Compiling TypeScript

To compile **TypeScript** files & watch for changes, navigate to the file directory and use

```bash
tsc -w
```

# TypeScript Features

With **TypeScript** setup, let's take a look at the features **TypeScript** has to offer.

## Types

Since **TypeScript** is a _strongly typed language_, it makes sense to start off with its **type system**. The variable types can be defined as follows

```ts
const userName: string = "John Doe";

let age: number;
age = 30;

const arr: number[] = [1, 2, 3]; // array
const tuple: [string, number] = ["John", 30]; // tuple (fixed size)

const nullValue = null; // infered type
```

**NOTE:** If you access `index > 1` in the tuple above or assign a _non-number_ value to `age`, **TypeScript** compiler will throw an error, making sure you fix the code before execution.

You can also create custom types to suit your specific needs.

```ts
type User = {
  name: string;
  age?: number; // Optional property (`age` can be undefined)
  (): number; // type is callable (returns number)
  new (name: string): User; // can be called as a constructor
  readonly id: string; // readonly property (cannot be modified after creation)
  signIn: (retryCount: number) => void; // function (takes a number as a parameter & returns void)
  customConstant: "constant"; // value can only be "constant"
  get fullName(): string;
  set username(name: string);
};

type UserAges = {
  [id: string]: number; // index signature (unspecified values can accept numbers)
};

type Pi = 3.14; // value type
const pi: Pi = 3.14;
```

**TypeScript** also allows you to create `union`, `intersection`, and `enum` types.

```ts
type Size = "small" | "medium" | "large"; // union type

type Coordinates = { x: number } & { y: number }; // intersection type ({ x: number; y: number })

enum SizeEnum {
  Small,
  Medium,
  Large,
} // enum type (the values will be assigned from 0 to N)

enum SizeStringEnum {
  Small = "small",
  Medium = "medium",
  Large = "large",
} // enum type (with string values)

const size: SizeEnum = SizeEnum.Small;
```

## Generics

In case you _don't know the type of the variable_, you can use `Generics` to allow the **compiler** to infer the type.

```ts
function clone<T>(o: T) {
  return JSON.parse(JSON.stringify(o)) as T;
}
```

## Interfaces

**TypeScript** also allows you to create `interfaces`. An `interface` defines the _shape_ of an object.

```ts
interface User {
  name: string;
  age?: number;
  (): number;
  new (name: string): User;
  readonly id: string;
  signIn: (retryCount: number) => void;
  customConstant: "constant";
  get fullName(): string;
  set username(name: string);
}
```

Looks similar to the `type` definition above? Now let's look at the true power of `interfaces`: they can be extended, used with `Generics`, and even used with classes.

```ts
// Extend an interface

interface Animal {
  leg: number;
}

interface Dog extends Animal {
  bark(): void;
}

const dog: Dog = {
  leg: 4,
  bark: () => console.log("Woof!"),
};

// Generics

interface APICall<Response> {
  data: Response;
}

const api: APICall<string> = {
  data: "Hello",
};
```

## Classes

Classes in **TypeScript** work very similar to **JavaScript**, with small differences. You have to _declare the types of the properties_ in the class, the _ability to combine interfaces_, _add access specifiers_, and _create abstract classes_.

```ts
// Implement an interface

interface IStorage {
  data: string;
}

class Store implements IStorage {
  data: string;

  constructor(d: string) {
    this.data = d;
  }
}

// Access Specifiers

class User {
  public id: string; // default specifier for data & methods is public
  private secret: string = "super secret string";

  constructor(id: string) {
    this.id = id;
  }
}

// Abstract classes

abstract class Animal {
  abstract getName(): string;
}

class Dog extends Animal {
  getName() {
    return "Dog";
  }
}
```

# Wrapping Up

Give yourself a pat on the back! You've now know **TypeScript**.

![pat on the back](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/js6znxu6neow6bst8h1x.gif)

Finally, my disciple, you are ready to start writing **TypeScript** code. Go ahead and try it out! _It is a bit difficult to get started_, but once someone does, _I have never heard them going back_ to **JavaScript** before!

**Happy Developing!**

Finding **personal finance** too intimidating? Checkout my **Instagram** to become a [**Dollar Ninja**](https://www.instagram.com/the.dollar.ninja/)

## Thanks for reading

Need a **Top Rated Front-End Development Freelancer** to chop away your development woes? Contact me on [Upwork](https://www.upwork.com/o/profiles/users/~01c12e516ee1d35044/)

Want to see what I am working on? Check out my [Personal Website](https://tapajyoti-bose.vercel.app) and [GitHub](https://github.com/ruppysuppy)

Want to connect? Reach out to me on [LinkedIn](https://www.linkedin.com/in/tapajyoti-bose/)

I am a freelancer who will start off as a **Digital Nomad** in mid-2022. Want to catch the journey? Follow me on [Instagram](https://www.instagram.com/tapajyotib/)

Follow my blogs for **Weekly new Tidbits** on [Dev](https://dev.to/ruppysuppy)

**FAQ**

These are a few commonly asked questions I get. So, I hope this **FAQ** section solves your issues.

1. **I am a beginner, how should I learn Front-End Web Dev?**
   Look into the following articles:

    1. [Front End Development Roadmap](https://dev.to/ruppysuppy/front-end-developer-roadmap-zero-to-hero-4pkf)
    2. [Front End Project Ideas](https://dev.to/ruppysuppy/5-projects-to-master-front-end-development-57p)