Typescript for Beginners
Tags: typescript, beginners, programming, webdev
Published: 2022-08-03 03:18:14

## Table Of Contents
[1. Introduction](#chapter-1)
[2. Purpose and Uses](#chapter-2)
[3. Functionalities and Examples](#chapter-3)
[4. Conclusion](#chapter-4)

Alright... Another week, another post! For this week, I will write about Typescript. I have been using typescripts in my project for my past few projects but only recently have I gotten serious about trying to understand the core functionalities of it. Hopefully this post is more beginner friendly. 

<a name="chapter-1">Introduction</a>
So what is Typescript? Well, from what I gathered from the documents, it is a superset of Javascript that builds on top of Javascript. So some consider it both a language and a set of productivity tools. Ohh.. and it is created by Microsoft and open source too.

![Typescript superset of Javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j49n52pvrbnrktb7mdfc.png)

Once a typescript project is deployed, typescript code is compiled into plain javascript using a typescript compiler. So instead of a file ending with `.js` when using Javascript, a typescript file will end with `.ts`. And if we are using react, your file will end with `.tsx` or `.ts`.

<a name="chapter-2">Purpose and Uses</a>
From my beginner's understanding, Typescript serves three core purposes as follows:
1. Since Javascript is a loosely typed language, Typescript introduces types to JavaScript with static typing. This is one of the main advantage for using Typescript.
2. It helps highlight some errors and bugs at the time of development and before deploying your projects.
3. It can be a productivity tool. Using features such as `enum`, `types`, `interface`, etc can create a richer IDE environment for providing _suggestions_ and _auto-corrections_ as we type.

<a name="chapter-2">Functionalities and Examples</a>
As mentioned above, Typescript have some fundamental types. Javascript already has some in built types such as `number`, `string`, `boolean`, `null`, `undefined`, and `object`. However, Typescript introduces even more of these such as `tuple`, `enum`, `never`, `unknown`, and `any`.

To start off, let's see what is the fuss about Typescript. We will create a variable call `money` and assign a type `number` to the variable in a Typescript file named index.ts

![Typescript file using number type](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t4he10piduoxz8acx8fm.png)

As seen from the image above, an error have appeared in line 5 with an error message `Type 'string' is not assignable to type 'number'.` As we have declared the variable `money` to be a `number` type, on line 5, when we assigned a string type to the `money` variable, the error was generated. If we were to type our code in a JavaScript file, the error will not be highlighted in our IDE as it is acceptable in JavaScript.

![Javascript file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uno55m5p718lnumrjvud.png)

On a side note, even if we do not explicitly assign a type `number` to the `money` variable, Typescript will implicitly assumes the type is a `number` as in the initial declaration, a number `10` was assigned to the variable. Take a look below how it works in our index.ts file:

![Without explicitly assigning a type](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fu3djgnsfg6tsfrlcihe.png)

As we can see, an error was generated as well. How cool is that! 

Moving on, for `number`, `string`, `boolean`, assigning of types is pretty straight forward. As for arrays, it requires a little more understanding. Lets say we want pass an array of strings into a function, to assign an array of strings, we can do the following:

![Array type assignment](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bnw7bpryxniljg91uxny.png)

By using the `[]` symbol to represent an array and the type of elements we expect in the array, we can explicitly assign a type. Hence in the example above, when we insert a `number` into the array, Typescript caught the error and alerted us.

Another advantage of using Typescript is having better code completion (IntelliSense) when typing your code. Lets take for the example below:

![InitelliSense](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dkdn1t3g0bv83s52py28.png)

In the code snippet, we can see that when the array element are assign to a `string` type, when we want to manipulate each element in the array using a `forEach` method, all the string methods are suggested to us. This help us to quickly scan and identify which method are available for us to use which can boost productivity.

Next we have functions. The way to apply Typescript in functions is as shown below:

![TypeScript for function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f8m2cbu4ohd1n6a4vace.png)
 
As seen above, besides assigning a type to the function argument, we also need to assign the type for the return value. Based on the example above, the type assigned for the return value is after the function brackets `:number`. However, if the function does not return anything, we will use `:void` instead. Also, if we want the argument being passed to the function to be optional, we can insert a `?` symbol such as `expenses?: number` to inform TypeScript this argument is optional.

Next on the list of types are Tuples. They are fix length array where each element have a particular type. For instance, we want to declare that for each movie, we want to represent the movie information by creating an array that have two values, movie name, box office amount. We can use the following syntax to annotate:

![Tuples](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tfa47bz32mc4jvkfgrxg.png)

Note that if only two elements were type assigned, only two elements can be declared in the array. No more, no less. For best practice, we typically only assign two values in a tuples. Anything more than that, the code readability suffers. Also, when we access the each elements in the array. For example `movies[0]` or `movies[1]`, you get the methods for strings and numbers respective with IntelliSense which helps with productivity.

Then there is the Enum type. The Enum allows us to group certain const together into a type and access it. For example, if we want to decide the price of food at three different serving sizes (small, medium and large). We can do it the old school way of declaring three different variables like what is shown below
```Javascript
const small = 3
const medium = 5
const large = 7
```
or we can use Enum to declare the variable
```javascript
const enum FoodCost {
  small = 3,
  medium = 5,
  large = 7,
}

let myFoodCost: FoodCost = FoodCost.medium;
```
Note that the declared name for the enum is in _Pascal_ case. In the example shown above, when we `console.log` `myFoodCost`, 5 will be logged in the console. One useful thing about Enum, we are able to export the Enum to other files to use. So typically, we can create a file just to store all our Enums and import it into different files to use.

Next, we have objects. We can assign a type for a object by this way:
```javascript
let food: {
  name: string;
  price: number;
  calories?: number;
} = {
  name: "fish and chips",
  price: 10,
  calories: 700,
};
```
By assigning the type this way, every key/value pair in the object is assigned a type. Also, we have assign the `calories` key/value pair to be optional. Which means if it was not declared in the object, an error will not be generated. However for `name` and `price` key/value pair, it must be declared in the `food` object or else Typescript will generate an error. Type assignment for Object are very useful as it keep a strict shape of the Object.

Lastly, we have the `any` type. We typically use this type if we want to bypass strict typing from Typescript. example would be:

```javascript
let movies:any = 'batman'
```
It is highly not recommended to do this as we are removing one of the key functionalities of Typescript. However in some cases, if we have an error which we cannot resolve and want to move forward with the project OR we want to run certain code first before assigning the correct types, we can use the `any` type. However as mentioned before, this will defeat the purpose of using Typescript in the first place.

Alright, I hope I have covered a fair bit of Typescript for beginners. Maybe for the next post, I will write about using Typescript specifically for React. To learn more about Typescript, refer to the official documentation at https://www.typescriptlang.org/docs/. Thanks for reading and stay safe!