What is TypeScript and why should you use it?
Tags: beginners, javascript, typescript, codenewbie
Published: 2021-05-14 12:49:52

## What is **TypeScript**?

**TypeScript** is a programming language developed and maintained by **Microsoft**. It introduces additional features like strict type binding (variables are bound to specific data types) to **JavaScript** and can also be compiled down to **JavaScript** as well.

**TypeScript** is an Open Source Project, and the source code for it is available on GitHub.

## What additional features does **TypeScript** introduce?

**TypeScript** adds several additional features to JavaScript. The most important one is strict typing (it is turned on by default, but can be turned off in case the developer doesn't want to use it).

Apart from strict typing, **TypeScript** introduces a plethora of features like _Interfaces_, _Mixin classes_, _Enums_ and much more, as discussed later in the article.

## Why should you use **TypeScript**?

If the features mentioned above weren't enough to convince you to use **TypeScript**, the following reason would definitely do so. **TypeScript** overcomes the largest issue with **JavaScript**; which is: a problem can only be detected during runtime in **JavaScript**, which may result in applications with bugs being shipped to the end-user. This will affect any business negatively by hampering the _user experience_. **TypeScript** removes this problem by checking for any issue at compile time.

The following script will not raise any errors when using **JavaScript**, but if you use **TypeScript**, the compiler will point out that `nonExistentProperty` doesn't exist on object `obj`

```js
const obj = {
	foo: "baz",
};

console.log(obj.nonExistentProperty);
```

Even if you are using an editor, using **TypeScript** provides you with better suggestions and linting as shown below:

![TypeScript Debug](https://learn.coderslang.com/ts-debug.png)

![JavaScript Debug](https://learn.coderslang.com/js-debug.png)

`getWeatherDetails()` will accept a boolean value which **TypeScript** points out, but **JavaScript** fails to do so.

## Getting Started with **TypeScript**

Enough theoretical stuff. Now let's get our hands dirty writing our first **TypeScript** script.

**NOTE**: You will need a **Node.js** and a package manager (**npm** or **yarn**, in this article, we will be using **npm**) installed to use **TypeScript** locally. You may use an online compiler like typescript playground for compiling, but it is not a good idea in the case of a large project.

To install **TypeScript** globally (replace the `-g` tag with `-D` to add it as a _dev dependency_ in a **Node** package), use the following command:

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

Now you will be able to compile any **TypeScript** code to **JavaScript**. Let's test it using a basic snippet:

```ts
const obj = {
	foo: "baz",
};

console.log(obj);
```

To compile the file use (you can also use the commands without installing **TypeScript** by adding `npx` before every command):

```bash
tsc <filename>.ts
```

You will find a new file `<filename>.js` created in the same folder, which can be run like any **JavaScript** file.

## **TypeScript** vs **JavaScript** dilemma

Now you might come up with 2 questions:

1. Why does the **TypeScript** code have to be compiled to **JavaScript**?
2. If the code compiles down to **JavaScript**, why would we bother writing it in **TypeScript**?

The answer to the first question is **TypeScript** isn't understood by any browser, so it has to be converted to **JavaScript** so that browsers can execute the code.

The answer to the second question would be, same as why you should use **TypeScript** over **JavaScript**, it offers type check at compile time as opposed to runtime. If you try to compile the `test.ts` with the error (as shown in _Why should you use **TypeScript**?_ section) the compiler would throw an error and warn you about the incorrect code.

## **TypeScript** features

As mentioned earlier, **TypeScript** has several additional features compared to **JavaScript**, we will be going over a few of them in this section.

### **Type System**

The default types available in **TypeScript** are given below:

|   Data    |     Type      | Keyword Description                                          |
| :-------: | :-----------: | ------------------------------------------------------------ |
|  Number   |  **number**   | Double-precision 64-bit floating-point values. It can be used to represent both, integers and fractions. |
|  String   |  **string**   | Represents a sequence of Unicode characters                  |
|  Boolean  |  **boolean**  | Represents logical values, true and false                    |
|   Void    |   **void**    | Used on function return types to represent non-returning functions |
|   Null    |   **null**    | Represents an intentional absence of an object value.        |
| Undefined | **undefined** | Denotes value given to all uninitialized variables           |

**TypeScript** also allows you to combine 2 or more data types to create a **Union**

```ts
let union: number | string;

union = 10;
union = "Hello World";

// union = true // ERROR!!! `union` can only be a number or a string
```

In the case of **JavaScript**, an error would have not been pointed out and might lead to bugs down the line.

### **Interfaces**

**TypeScript** **Interface** allows you to describe how an object would look like, something that is not possible in **JavaScript**.

```ts
// Interfaces for Objects
interface IObjectDefination {
	foo: number[]; // foo is a number array
	baz: Date; // baz is a date
	[key: number]: string; // any other key (only numbers) can contain a string as its value
}

let obj: IObjectDefination;

// Interfaces for Classes
interface IClassDefination {
	data: string;
	func: () => void;
}

class Class implements IClassDefination {
	data: string;

	func() {
		return;
	}
}
```

### **Enums**

**Enums** allow a developer to define a set of named constants, making it easier to document intent or create a set of distinct cases.

```ts
enum Direction {
	Up,
	Down,
	Left,
	Right,
}

function move(direction: Direction) {
	// ...
}

move(Direction.Up);
move(Direction.Down);
```

Achieving a _similar_ result with **JavaScript** would require you to create an object with the respective keys. Even then we would not be able to specify the data type of `direction` in `move()`.

```js
const Direction = {
	Up: "Up",
	Down: "Down",
	Left: "Left",
	Right: "Right",
};
```

## Streamlining **TypeScript** compilation

Earlier we used `tsc` to compile a single **TypeScript** file. This may become a problem in the case of a large project with thousands of files. In that case, you can set up a listener to watch for changes.

For watching for changes, you need to create a `tsconfig.json` file in the root directory of your project and add the following:

```json
{
	"compilerOptions": {
		"target": "es5",
		"module": "commonjs",
		"strict": true,
		"outDir": "dist"
	},
	"include": ["src"],
	"exclude": ["node_modules", "dist"]
}
```

Alternately, you may use `tsc --init` to create the file (it is generated pre-configured and with all options, the unnecessary ones commented out).

Now you can set up the listener

```bash
tsc -w
```

Now, any **TypeScript** file you create or modify in the `src` (_tsconfig.include_) folder will be compiled to **JavaScript** file in the `dist` (_tsconfig.compilerOptions.outDir_) folder whenever you make any changes.

**NOTE**: You can add the `tsconfig.json` to any of your **Node** packages and convert it from a **JavaScript** project to a **TypeScript** one.

## Conclusion

In this article, we went through what **TypeScript** is and how it can help you write better code. We saw some features it offers and how certain features like _Enums_ and _Interfaces_ can make your life a little easier. Now it's time for you to add **TypeScript** to your very own project!

[Learn Full-Stack Web Development](https://js.coderslang.com)