DEV Community

Cover image for JavaScript on Steroids: Why and How Pros use TypeScript
Tapajyoti Bose
Tapajyoti Bose

Posted on • Updated on • Originally published at tapajyoti-bose.Medium

JavaScript on Steroids: Why and How Pros use TypeScript

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

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.

npm install -g typescript
Enter fullscreen mode Exit fullscreen mode

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

npm install -D typescript
Enter fullscreen mode Exit fullscreen mode

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

tsc --init
Enter fullscreen mode Exit fullscreen mode

Compiling TypeScript

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

tsc -w
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

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.

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;
Enter fullscreen mode Exit fullscreen mode

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

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;
Enter fullscreen mode Exit fullscreen mode

Generics

In case you don't know the type of the variable, you can use Generics to allow the compiler to infer the type.

function clone<T>(o: T) {
  return JSON.parse(JSON.stringify(o)) as T;
}
Enter fullscreen mode Exit fullscreen mode

Interfaces

TypeScript also allows you to create interfaces. An interface defines the shape of an object.

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);
}
Enter fullscreen mode Exit fullscreen mode

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.

// 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",
};
Enter fullscreen mode Exit fullscreen mode

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.

// 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";
  }
}
Enter fullscreen mode Exit fullscreen mode

Wrapping Up

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

pat on the back

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

Thanks for reading

Need a Top Rated Front-End Development Freelancer to chop away your development woes? Contact me on Upwork

Want to see what I am working on? Check out my Personal Website and GitHub

Want to connect? Reach out to me on LinkedIn

I am a freelancer who will start off as a Digital Nomad in mid-2022. Want to catch the journey? Follow me on Instagram

Follow my blogs for Weekly new Tidbits on Dev

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
    2. Front End Project Ideas

Top comments (3)

Collapse
 
ruppysuppy profile image
Tapajyoti Bose

Thanks for investing so much time to improve the article :)

Collapse
 
devto2k5 profile image
dev procedure

I do NOT see "real-world" problem being solved by using TypeScript.

All I see are silly examples of a "function that adds or divides 2 numbers' to justify "type checking". e.g., Who writes a function just to do basic math????

Next, developers are testing (aka runtime) their code LINE-BY-LINE anyway, so "compile-time" checking isn't all that beneficial in saving a developer time.

In other words, TypeScript add a layer of complexity that doesn't have that much benefit to JavaScript world.

NEWS FLASH:

  1. Most data on the Client Side are STRINGS anyway.
  2. NUMBERS and DATES are already validated in the client's browser anyway.
Collapse
 
yw662 profile image
yw662 • Edited

Exactly what I was trying to say about this article :-)
(All except I don't use the hash mark)