Introduction to TypeScript
Tags: javascript, typescript, node, vscode
Published: 2020-05-25 03:33:43


## Why TypeScript?

When I decided to pursue a career as a computer programmer, there was an important decision to make. Which language should I learn first as my point of entry? JavaScript seemed like a logical choice. It is ubiquitous in web development. It’s versatile and easy to learn. I soon learned, it is also very quirky.

For one, JavaScript is dynamically typed. The type of a variable, e.g. number, string, object, is associated with its run-time value. In practice, this means that a variable can change type via reassignment or through another operation without throwing an error. This allows developers to code quickly without worrying about whether type is consistently maintained. 

Unfortunately, this can lead to unpredictable bugs that are hard to track down without debugging line by line. In a small application, like animating an element on a web page, this trade-off of speed vs. care could be worthwhile. Historically, this was JavaScript’s domain. 

However, as the JS community has continued to grow, JS applications have grown in scale and complexity. These type related bugs can cause major headaches.

![sneetches javascript meme](https://dev-to-uploads.s3.amazonaws.com/i/eji2p5wahuqdzc7bbc6j.jpg)

TypeScript was developed by Microsoft in 2012 to grant the vast community of JS developers easy access to a statically typed language, that is more suitable for the complexity of modern JS applications. 

## Getting Started with TypeScript in VS Code

Before we get started, let’s install the necessary packages in node so we can experiment in VS Code. For our purposes of experimentation, the following two lines are enough. Run them in the terminal to install the necessary dependencies. If you don't have node and npm installed, make sure to do that first.

```
npm install -g typescript
npm install -g ts-node
```

This will allow us to compile our TS files into JS, and also test our TS files directly in the terminal. 

Next let's make a file called type.ts. VS Code will automatically provide language support for TS files that end with the extension .ts.


## Assigning Types

The first thing to know about TypeScript is that it is a superset of JavaScript, or JavaScript with extra features. This means that all existing JS syntax is valid in TS, so you can use any of your favorite libraries when coding in TS. Furthermore, TypeScript compiles into plain JavaScript. So when you run your code that you wrote in TS, you are running JS. This means that any code you write will run in any browser or node environment.

TypeScript enforces strict rules regarding type as you code. You can’t reassign a variable that should be an array into a string. Let's create some variables from the three main primitive types.

```typescript
const make: string = 'honda';
const color: string = 'gold';
const year: number = 2006;
const isReliable: boolean = true;
```

It is good practice to assign a type when creating a variable but TypeScript can infer all of the types above if standard JavaScript syntax is used. 

Let's create a car object with that information.

```typescript
const myCar = { make, color, year, isReliable };
```

Next let's create a function to paint our car a new color. Notice that we have an opportunity to assign types to parameters in functions as well. If we chose not to assign a type in the function parameters, it will default to the 'any' type. Although this would technically work, we will be missing out on some powerful IDE features granted by TypeScript.

```typescript
const paintCar = (car: object, color: string) => {
  car.color = color; // Property 'color' does not exist on type 'object'.
  return car;
}
```

Uh oh! We have encountered our first error. This is because TypeScript doesn't merely enforce type, but also the shape of complex datatypes like objects and arrays. In other words, the values of the keys or indices also have types associated with them.  So even though the type of the car is an object, we will need to be a little more specific.

Let's create an interface!

```typescript
interface Car {
  make: string;
  color: string;
  year: number;
  isReliable: boolean;
  soundSystem?: string;
}
```
An interface describes the type requirements of the properties of an object. In the example above, all the properties are required except for sound system. The ? denotes an optional parameter. Let's try our function again and log the result to the console.

```typescript
const paintCar = (car: Car, color: string) => {
  car.color = color;
  return car;
}

console.log(paintCar(myCar, 'zebra'));
```

In the terminal, navigate to the directory containing your type.ts file and run the following command. This allows our TS file to be tested in the node environment similar to using the node command. Make sure you install ts-node using npm first.

```
ts-node type.ts
// logs { make: 'honda', color: 'zebra', year: 2006, isReliable: true }
```

A powerful benefit of using TypeScript is that your IDE knows at any given time what type and properties exist on your objects. Take our contrived example, which returns the car object after changing the color. This means that any function invocation can be chained with a property of the car object. Optional properties are shown with a question mark. 

```typescript
paintCar(myCar, 'zebra'). // IDE shows color, make, isReliable, soundSystem?, year as options
```
This is a wonderful time saver when working deep in a complicated project. You don't need to insert console logs everywhere to find out what the data structures are. Your IDE can simply tell you at any given time. 

## Compiling

Finally, once your TypeScript file has been written, simply run the following command to compile the file into JavaScript. type.js will appear in the same directory, ready to be implemented wherever JS is supported.

```
tsc type.ts
```
## Conclusion

I've just scratched the surface of TypeScript, but honestly I can't wait to start implementing it in my projects. One of my greatest frustrations in web development is keeping track of complicated data structures deep inside of nested callbacks. TypeScript makes this a breeze. Any large scale JavaScript project would benefit tremendously from its type control features.