TypeScript for Beginners, Part 1: Getting Started

Let’s start this tutorial with the question: “What is TypeScript?”

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. As an analogy, if JavaScript were CSS then TypeScript would be SCSS.

All the valid JavaScript code that you write is also valid TypeScript code. However, with TypeScript, you get to use static typing and the latest features that get compiled to plain JavaScript, which is supported by all browsers. TypeScript is aimed at solving the problem of making JavaScript scaleable, and it does a pretty good job.

In this tutorial, you will begin by reading about different features of TypeScript and why learning it is a good idea. The rest of the sections in the article will cover the installation and compilation of TypeScript along with some popular text editors that offer you support for the TypeScript syntax and other important features.

Why Do We Need TypeScript?

We use programming languages to instruct computers how we want them to do something. They basically act as a medium of communication. However, computers don’t actually directly understand the JavaScript, PHP or Python code that we write. All the human readable code that we write is ultimately converted to machine code which the computers can run and understand.

Modern programming languages are written with the needs of the programmer in mind. This means that different programming languages are designed with different feature set due to the way they are meant to be used. JavaScript was written to be very easy to use language and get things done by writing minimal amount of code.

JavaScript has become a lot more popular since its early days and is now widely used for small- as well as large-scale projects. Some limitations of JavaScript that were acceptable when writing small programs can hamper productivity when working on large projects with many team members.

TypeScript was created to address these limitations by adding a variety of features like type-checking to help you quickly catch any errors that might crop up when making changes to code in large-scale projects.

Why Learn TypeScript?

If you have never used TypeScript before, you might be wondering why you should bother about learning it at all when it compiles to JavaScript in the end.

Let me assure you that you won’t have to spend a lot of time in learning TypeScript. Both TypeScript and JavaScript have very similar syntax, and you can just rename your .js files to .ts and start writing TypeScript code. Here are a few features that should convince you to start learning TypeScript:

Unlike JavaScript, which is dynamically typed, TypeScript allows you to use static typing. This feature itself makes the code more maintainable and greatly reduces the chances of bugs that might have been caused due to incorrect assumptions about the type of certain variables. As an added bonus, TypeScript can determine the type of a variable based on its usage without you explicitly specifying a type. However, you should always specify the types for a variable explicitly for clarity.
To be honest, JavaScript was not designed to serve as a large-scale development language. TypeScript adds all these missing features to JavaScript that make it truly scaleable. With static typing, the IDE that you are using will now be able to understand that code that you are writing in a better way. This gives the IDE the ability to provide features like code completion and safe refactoring. All this results in a better development experience.
TypeScript also allows you to use all the latest JavaScript features in your code without worrying about browser support. Once you have written the code, you can compile it to plain old JavaScript supported by all browsers with ease.
A lot of popular frameworks like Angular and Ionic are now using TypeScript. This means that if you ever decide to use any of the frameworks in future, learning TypeScript now is a good idea.

I would also like to add that planning to learn TypeScript does not mean you have to unlearn a lot of JavaScript. The program logic flows the same way in both TypeScript and JavaScript. The only thing that changes in the type-checking during compile time.

Installation

Before you start writing some awesome TypeScript code, you need to install TypeScript first. This can be done with the help of npm. If don’t have npm installed, you will have to install npm first before installing TypeScript. To install TypeScript, you need to start the terminal and run the following command:

npm install -g typescript

Once the installation is complete, you can check the TypeScript version that was installed by running the command tsc -v in your terminal. If everything was installed properly, you will see the installed TypeScript version number in the terminal.

IDEs and Text Editors With TypeScript Support

TypeScript was created by Microsoft. So the fact that Visual Studio was the first IDE to support TypeScript should not come as a surprise. Once TypeScript started gaining popularity, more and more editors and IDEs added support for this language either out of the box or through plugins. Another lightweight and open-source editor called Visual Studio Code, created by Microsoft, has built-in support for TypeScript. Similarly, WebStorm also has out-of-the-box support for TypeScript.

Microsoft has also created a free Sublime TypeScript Plugin. NetBeans has a TypeScript plugin that provides variety of features for ease of development. Syntax highlighting is available in Vim and Notepad++ with the help of the typescript-vim and notepadplus-typescript plugins respectively.

You can see a full list of all the text editors and IDEs that support TypeScript on GitHub. For the examples in this series, I will be using Visual Studio Code to write all the code.

The Difference Between TypeScript and JavaScript

From a programmer’s point of view, TypeScript is a superset of JavaScript. It introduces some additional features that help you write code with lower chances of introducing an unintentional bug. However, all that TypeScript code you write is eventually compiled into JavaScript for the computer to run. This basically means that there is nothing that you can do in TypeScript but won’t be able to implement with JavaScript alone.

Even though TypeScript introduces type-checking to make sure different variables are not assigned values willy-nilly, it does not interfere with the syntax and runtime behavior of the language. Lets see some basic code snippets to see how TypeScript differs from JavaScript.

JavaScript has the const keyword to specify that we want to prevent any changes to the value of that variable through reassignment or prevent its re-declaration. However, this doesn’t mean that the value of the variable is immutable. There are still other ways to change it. Here is an example:

const fruits = [“Apples”, “Mangoes”, “Bananas”];
const vegetables = [“Potatoes”, “Onions”, “Cucumbers”];

fruits.push(“Orange”);
// [“Apples”, “Mangoes”, “Bananas”, “Orange”]

fruits[0] = “Papayas”;
// [“Papayas”, “Mangoes”, “Bananas”, “Orange”]

fruits = vegetables // Error

Up until the last line, the above code is perfectly valid JavaScript and won’t throw any errors. We declared fruits to be a constant. However, we were still able to change its value using other means. What if this isn’t the intentional behavior? You can use TypeScript to make sure that the value of fruits cannot be changed by any means once it has been declared a constant.

let fruits = [“Apples”, “Mangoes”, “Bananas”] as const;
let vegetables = [“Potatoes”, “Onions”, “Cucumbers”] as const;

fruits.push(“Orange”); // Error
fruits[10] = “Papayas”; // Error

Trying to compile the above code will result in errors because we have declared fruits to be read-only.

Similarly, JavaScript allows us to access object properties that don’t even exist. Instead of throwing an error, you get back undefined as a value. This approach makes sense because it allows us to dynamically add, remove or update an object’s properties. However, it can also be a source of errors or unexpected behavior. Here is an example:

let guy = {
name: ‘Mario’,
age: 56
}

console.log(guy.name + ‘ is ‘ + guy.ahe + ‘ years old.’);
// Mario is undefined years old.

Mistyping age as ahe is not considered an error in JavaScript but it would have been caught in TypeScript. Try compiling the above code from TypeScript to JavaScript and you will see an error about ahe not being an existing property.

Lets move on to function definitions now. JavaScript does not have a built-in concept of matching the number of arguments passed during a function call to the number of arguments mentioned in the function definition. This might not seem like a big deal but it has the potential to make the code very hard to manage when working on projects with thousand of functions spread over hundreds of files. Some capable IDEs can make things easier but it is still nice to have such features built-into the language.

Here is an example of some code that is run directly as JavaScript. As you can see, JavaScript does not care how many and what type of arguments are passed to the function perimeterTriangle(). This results in some nonsensical value being output as the perimeter of our triangle.

function perimeterTriangle(a, b, c) {
console.log(`Perimeter of the triangle is: ${a + b + c}`);
}

perimeterTriangle(20, 30, “Potato”);
// Perimeter of the triangle is: 50Potato

perimeterTriangle(“Potato”, 10);
// Perimeter of the triangle is: Potato10undefined

perimeterTriangle();
// Perimeter of the triangle is: NaN

perimeterTriangle(20, 30, 50);
// Perimeter of the triangle is: 100

Even if you don’t make any changes to the above code and try to compile it from TypeScript to JavaScript, you will still get errors with the second and third function calls due to mismatch in the number of arguments provided. However, we can add more information to our function definition by specifying the type of arguments that we expect the function perimeterTriangle() to accept.

function perimeterTriangle(a: number, b: number, c: number) {
console.log(`Perimeter of the triangle is: ${a + b + c}`);
}

perimeterTriangle(20, 30, “Potato”);
// Error: Argument of type string not assignable to type number.

perimeterTriangle(“Potato”, 10);
// Error: Expected three arguments but got 2.

perimeterTriangle();
// Error: Expected three arguments but got 0.

perimeterTriangle(20, 30, 50);
// Perimter of the triangle is 100.

Now, even the first function call throws an error due to the mismatch in argument type. TypeScript will help you catch many such errors and save a lot of time in the long run.

Compiling TypeScript to JavaScript

Let’s say you have written some TypeScript code in a .ts file. Browsers won’t be able to run this code by themselves. You will have to compile the TypeScript into plain JavaScript that can be understood by browsers.

If are using an IDE, the code can be compiled to JavaScript in the IDE itself. For example, Visual Studio allows you to directly compile the TypeScript code to JavaScript. You will have to create a tsconfig.json file where you specify all the configuration options for compiling your TypeScript file to JavaScript.

The most beginner-friendly approach when you are not working on a large project is to use the terminal itself. First, you have to move to the location of the TypeScript file in the terminal and then run the following command.

tsc first.ts

This will create a new file named first.js in the same location. Keep in mind that if you already had a file named first.js, it would be overwritten.

If you want to compile all the files inside the current directory, you can do so with the help of wildcards. Remember that this will not work recursively.

tsc *.ts

Finally, you can only compile some specific files by explicitly providing their names in a single line. In such cases, JavaScript files will be created with corresponding file names.

tsc first.ts product.ts bot.ts

Let’s take a look at the following program, which multiplies two numbers in TypeScript.

let a: number = 12;
let b: number = 17;

function showProduct(first: number, second: number): void {
console.log(“The product is: ” + first * second);
}

showProduct(a, b);

The TypeScript code above compiles to the following JavaScript code when the targeted version is set to ES6. Note how all the type information that you provided in TypeScript is now gone after the compilation. In other words, the code gets compiled to JavaScript that can be understood by the browser, but you get to do the development in a much better environment which can help you in catching a lot of bugs.

let a = 12;
let b = 17;
function showProduct(first, second) {
console.log(“The product is: ” + first * second);
}
showProduct(a, b);

In the above code, we have specified the type of variables a and b as numbers. This means that if later you try to set the value of b to a string like “apple”, TypeScript will show you an error that “apple” is not assignable to the type number. Your code will still compile to JavaScript, but this error message will let you know that you made a mistake and help you avoid a problem during runtime.

Here is a screenshot that shows the error message in Visual Studio Code:

Generated by Feedzy