DEV Community

Cover image for Typescript for Beginners
Jareth Tan
Jareth Tan

Posted on

Typescript for Beginners

Table Of Contents

1. Introduction
2. Purpose and Uses
3. Functionalities and Examples
4. Conclusion

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.

Introduction
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

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.

Purpose and Uses
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.

Functionalities and Examples
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

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

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

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

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

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

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

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

const small = 3
const medium = 5
const large = 7
Enter fullscreen mode Exit fullscreen mode

or we can use Enum to declare the variable

const enum FoodCost {
  small = 3,
  medium = 5,
  large = 7,
}

let myFoodCost: FoodCost = FoodCost.medium;
Enter fullscreen mode Exit fullscreen mode

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:

let food: {
  name: string;
  price: number;
  calories?: number;
} = {
  name: "fish and chips",
  price: 10,
  calories: 700,
};
Enter fullscreen mode Exit fullscreen mode

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:

let movies:any = 'batman'
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)