7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
Advertisement
  1. Code
  2. TypeScript

TypeScript for Beginners, Part 1: Getting Started

Read Time: 12 mins
This post is part of a series called TypeScript for Beginners.
TypeScript for Beginners, Part 2: Basic Data Types

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 the 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 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 sets due to the way they are meant to be used. JavaScript was written to make it very easy to get things done by writing a minimal amount of code.

JavaScript has become a lot more popular since its early days and is now widely used for small- and 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 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:

  1. 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.
  2. 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.
  3. 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.
  4. 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 is 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 you don't have npm installed, you will have to install npm before installing TypeScript. To install TypeScript, you need to start the terminal and run the following command:

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, also 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 a 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 that you 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. Let's 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:

Up to 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 intended 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.

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

TypeScript compiling ErrorsTypeScript compiling ErrorsTypeScript compiling Errors

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:

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.

Let's 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 a nonsensical value being output as the perimeter of our triangle.

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 a 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.

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.

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.

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.

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

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.

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:

type error in TypeScript

The above example shows how TypeScript keeps giving you hints about possible errors in code. This was a very basic example, but when you are creating very large programs, messages like these go a long way in helping you write robust code with less chance of error.

Final Thoughts

This getting started tutorial in the series was meant to give you a very brief overview of different TypeScript features and help you install the language along with some suggestions for IDEs and text editors that you can use for development. The next section covered different ways of compiling your TypeScript code to JavaScript and showed you how TypeScript can help you avoid some common errors.

I hope you liked this tutorial. The next tutorial of the series will discuss different variable types available in TypeScript.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Scroll to top
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.