Learn TypeScript 3 by Building Web Applications

3 (1 reviews total)
By Sebastien Dubois , Alexis Georges
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Introduction to TypeScript

About this book

TypeScript is a superset of the JavaScript programming language, giving developers a tool to help them write faster, cleaner JavaScript. With the help of its powerful static type system and other powerful tools and techniques it allows developers to write modern JavaScript applications.

This book is a practical guide to learn the TypeScript programming language. It covers from the very basics to the more advanced concepts, while explaining many design patterns, techniques, frameworks, libraries and tools along the way. You will also learn a ton about modern web frameworks like Angular, Vue.js and React, and you will build cool web applications using those. This book also covers modern front-end development tooling such as Node.js, npm, yarn, Webpack, Parcel, Jest, and many others. Throughout the book, you will also discover and make use of the most recent additions of the language introduced by TypeScript 3 such as new types enforcing explicit checks, flexible and scalable ways of project structuring, and many more breaking changes.

By the end of this book, you will be ready to use TypeScript in your own projects and will also have a concrete view of the current frontend software development landscape.

Publication date:
November 2019
Publisher
Packt
Pages
804
ISBN
9781789615869

 

Introduction to TypeScript

In this first chapter, we start by looking back in time in order to explain how the JavaScript language has evolved since its creation. This will help us to better understand why/where TypeScript comes into the picture.

We begin by illustrating the problems of vanilla JavaScript. Then, we will turn our attention to TypeScript.

This chapter also states how TypeScript can improve code quality and a developer's life, and help larger teams, by making it possible to create solid and easier-to-maintain code bases.

After that, we review some of the tools that you will need to work on the projects provided in the book and cover how to install each of them. This includes the code editor, the JavaScript runtime, the package manager, a source control management system, TypeScript, and more.

We will also see how to write the famous Hello World program with TypeScript and you'll learn a few things about variable declarations and basic TypeScript types.

In this chapter, we will cover the following topics:

  • Overview of the current frontend software development landscape
  • What is TypeScript and how does it help to improve code quality?
  • Similarities between .NET (C#), Java, and TypeScript
  • The minimum level of toolkit necessary for frontend development
  • How to install Visual Studio Code
  • How to install Git
  • How to install Node.js and npm
  • How to update npm
  • Where are npm packages installed?
  • How to install TypeScript
  • Introduction to basic TypeScript types (boolean, number, string, string literals)
  • Variable declarations: var versus let versus const
  • Basic functions
  • How to write the Hello World program in TypeScript
 

TypeScript in a few words

The TypeScript programming language (http://www.typescriptlang.org) was created by Microsoft and was later open sourced under the Apache 2.0 license. The source code of the language is available on GitHub over at https://github.com/Microsoft/TypeScript. At the time of writing, TypeScript now has 51,705 stars and 7,116 forks on GitHub and its popularity continues to rise.

The first thing to realize is that TypeScript compiles to JavaScript. This means that the output of the TypeScript compiler can run wherever JavaScript code can run, which actually means, nowadays, basically everywhere, since JavaScript can run in the following:

  • Web browser
  • Backend (for example, with Node.js)
  • Desktop (for example, with Electron)
  • Mobile, with frameworks such as React Native, NativeScript, Ionic, and many others
  • The cloud, with platforms such as Azure Functions, Google Cloud Functions, and Firebase

As stated earlier, TypeScript is compiled and not interpreted like JavaScript is. Actually, people often talk about transpilation rather than compilation in the case of TypeScript, since the TypeScript compiler actually does source-to-source transformation.

The second key point is that TypeScript is a superset of JavaScript as shown in the following diagram:

This means that any valid JavaScript code is also valid TypeScript code. This is great because it means that it is very easy to introduce TypeScript into an existing JavaScript code base. It does not stop there, though! As you'll see throughout the book, TypeScript adds a lot over vanilla JavaScript.

A third takeaway is that TypeScript is (optionally) typed. If you're familiar with JavaScript, then you probably know that it is a dynamically and weakly typed language. As any JavaScript code is also valid TypeScript code, it also means that you can declare variables without specifying their type and later assign different types to them (for example, numbers, strings, and more).

Although the fact that defining types is optional by default in TypeScript does not mean that you should avoid defining types. Instead, TypeScript shines when you make clever use of its type system.

TypeScript allows you to clearly specify the type of your variables and functions. In addition, it also has very powerful type inference, support for classes, generics, enums, mixins, and many other cool things that we’ll see throughout the book.

We'll see later in the book how to configure the TypeScript compiler to be stricter and we'll also learn the benefits of enforcing and leveraging strong typing at work, as well as for personal projects.

This quick introduction to TypeScript is useful for you to grasp what it is, but it does not explain why it exists and why it makes sense for you to use it.

 

JavaScript

Before we begin our TypeScript journey, it is useful to take a look back at JavaScript and where it comes from.

JavaScript's history in a nutshell

Before we go any further, we should take some time to briefly discuss the history of JavaScript and how it has evolved in recent years. You probably know that JavaScript is the core language of the web. It's actually a very versatile language that supports different programming paradigms such as imperative, object-oriented, functional, and event-driven programming.

As mentioned in the previous section, JavaScript can now be used almost everywhere, but that was not always the case. The language was initially designed by Brendan Eich (https://brendaneich.com) around 1995 (more than 20 years ago!) for the Mosaic web browser. The first version of the language was written in 10 days (!) and was called Mocha, and was later renamed to LiveScript. The whole story is very interesting and well worth reading.

It is important to realize that JavaScript has been here for a very long time and has also evolved a lot, especially since 2005, and more than ever since 2015.

ECMAScript

Another important thing to understand is that behind JavaScript, there is actually a language specification called ECMAScript, standardized by Ecma International in ECMA-262 since 1996. Though reading about it will be time consuming for now and not mandatory in order to understand further topics, you should know that this specification governs what JavaScript is and how it evolves. New language features and API proposals all go through the Ecma TC39 technical committee, which decides which ones are mature enough to make it into the specification. This all happens in the open, so don't hesitate to go and check it out.

ECMAScript evolution and support

The version of JavaScript that most developers around the world are familiar with is ES5, which was released in 2009. It included strict mode, accessors, syntax changes, meta-programming, and, most importantly, support for JSON.

Since 2015, ECMAScript, and thus JavaScript, has rapidly evolved. The specification now has a yearly release schedule, meaning that a new version is released each year. Thanks to this evolution, each year, all of the language change proposals that are mature enough get included in the new version of the specification. This follows a trend that we can see throughout the industry to increase the pace at which things evolve. It is very disruptive for large enterprises but is great for innovation.

In 2015, ECMAScript 6 was released and was later renamed ES2015. Since then, ES2016, ES2017, ES2018, and ES2019 have been released in the respective years.

Note that ESNext will always refer to the next version with the proposals that have not been finalized yet.

Make sure to stop by Dr. Axel Rauschmayer's blog (http://2ality.com) to learn more. Comparatively, ES2015 was incredibly big compared to the following iterations.

As you can imagine, it takes time for browser vendors and JavaScript engine developers to integrate newly standardized elements of the language. With ES2015, this meant that things such as let, const, classes, and many other features could not be used directly. This led to the increase in popularity of transpilation using tools such as Babel or TypeScript. Basically, the idea is to be able to use the newest features of the specification in your code right now and to transpile it so that it can run in environments that don't support those features just yet.

JavaScript gotchas

Now that you know a bit more about the history of JavaScript, and before we finally dive into TypeScript, we need to learn about the importance of knowing JavaScript, with its good and bad parts.

As you now know, JavaScript was initially created in 10 days, so it had issues, some of which are, unfortunately, still here today. The TypeScript compiler will protect you from some of these issues but it can't change things that are fundamental in JavaScript such as how numbers are represented.

Here are a few examples of things that are surprising (to say the least) in JavaScript:

  • JavaScript variables declared with var are function-scoped. For example, if you declare a variable in a for loop, then that variable declaration actually gets hoisted (that is, moved) to the top of the enclosing function. Block scoping is only possible since ES2015 with the let and const keywords (which you should always use instead of var!).
  • JavaScript's number type supports only 64-bit doubles (IEEE 754 double precision standard). Integers are represented as floating point variables; that is, some precision is lost once numbers get too large. Here's an example where it breaks: 9999999999999999 === 10000000000000000 evaluates to true!
  • typeof(NaN) evaluates to number.
  • true == 1 evaluates to true because == does type coercion (that is, converts the type).
  • null == undefined evaluates to true.
  • 42 == [42] evaluates to true: in conclusion, always prefer === and !== over == and !=.
  • 0 == '' evaluates to true.
  • null == undefined evaluates to true.
  • alert((![]+[])[+[]]+(![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]);: Displays an alert box with the message fail. Check out the JSF*ck website to know more about this one. Needless to say, hackers love these kinds of things!

The list could go on and on but we will leave it here. As mentioned earlier, TypeScript transpiles into JavaScript, which means that you need to have a good understanding of JavaScript, even if you program in TypeScript, and have knowledge about its good and bad parts.

Douglas Crockford has written a lot and given many talks about JavaScript. He has covered at great length JavaScript's weaknesses and strengths and we really recommend you watch some of his talks and read his book. You'll have fun while doing so and you'll discover many things that you should avoid at all costs in JavaScript as well as some that are really worth using. For a quick review, you can also check out the following summary: https://github.com/dwyl/Javascript-the-Good-Parts-notes.

Mr. Crockford has also created JSLint, a JavaScript linter (that is, a code quality checker) that helps to avoid dangerous syntax and detect possible mistakes before it is too late. A similar tool exists for TypeScript and is called TSLint.

 

How can TypeScript help?

Now that we've introduced TypeScript and have briefly covered JavaScript's history, evolution, and gotchas, we can finally discuss why TypeScript is relevant and why you should use it.

Enhanced JavaScript

First and foremost, TypeScript does not aim to replace JavaScript; instead, it aims to improve the lives of developers by providing a more powerful language that generates clean and simple JavaScript code. In a way, you could consider TypeScript as a code quality checker for JavaScript on steroids.

Future JavaScript today

A second big benefit is that TypeScript allows you to use the newest ECMAScript features right now, whether you're targeting the latest version of Node.js or Internet Explorer 11 (poor soul!). This is great because it means that you don't need to wait until everything is supported in the target environment.

You can very easily configure the TypeScript compiler to generate ES3-, ES5-, ES2015-, ES2016-, ES2017-, ES2018-, ES2019-, or ESNext-compatible code.

To make this clearer, let's take an example. In TypeScript, you can create classes while transpiling your code to ES3-compliant code, even though classes were only introduced in ES2015. The TypeScript compiler only performs transformations to use language constructs that existed in that version of ECMAScript. When TypeScript does this, we often talk about down-level emitThere are many features of most recent ECMAScript versions that you can use with TypeScript while targeting ES5.

Static typing

One of the best features of TypeScript is its powerful type system added on top of JavaScript. This alone should appeal to any developer who is used to working with strongly typed languages, and thus, used to benefiting from great IDE support.

When you develop using C# or Java with a solid editor/IDE, you get powerful auto-completion, refactoring support, access to the documentation, in-context hints, and warnings and errors, all for free. TypeScript provides the same developer experience for the JavaScript ecosystem and allows developers to benefit from a highly productive development environment. This is great for all developers, not only larger teams.

Whether you're a fan of static or dynamic typing, TypeScript will make you happy as types in TypeScript are optional and TypeScript has very powerful type inference capabilities. Moreover, type inference improves with each new release of the compiler.

Put simply TypeScript definitely will help you discover bugs earlier and it will help you to better organize and structure your code, whether you're working on a small application or a large project.

Structural typing

In TypeScript, usually, if things quack like ducks, then TypeScript assumes that they're ducks. Duck typing as it is called is baked into the language. We can say that TypeScript considers the compatibility of types. We’ll leverage this great feature in the projects to make things clear.

To give you an idea, if some function expects to receive an object of a Foo type and is instead called with an object of a Bar type, then TypeScript will not complain as long as Bar has the same structure as Foo. That is to say, a Bar object can be considered to be Foo if it exposes at least the expected properties/methods.


This is an oversimplification as there are actually many rules at play, depending on the considered types.

Structural typing is very useful as it helps avoid writing quite some boilerplate code; one example is when you have two equivalent data structures. In programming languages that don't support structural typing, you have to manually convert from one type to the other, just because the compiler doesn't recognize the structural compatibility of the types.

TypeScript does also supports some nominal typing (that is, non-structural). Nominal typing is interesting for cases where you want to distinguish objects with different types, even if their structure is identical.

We won't be covering nominal typing specifically in this book as it is more advanced, but do check out the following link if you're curious: https://basarat.gitbooks.io/typescript/docs/tips/nominalTyping.html.

Types for JavaScript libraries

Having auto-completion and type information for third-party libraries that you use is a huge time saver and it can also help you avoid many bugs. Now, you might wonder how TypeScript can provide you with type information for third-party libraries when they are not written themselves in TypeScript. Well, the TypeScript team and the community have got you covered!

TypeScript supports type definitions, also known as typings. Type definitions are sets of declarations that provide additional information to the compiler (somewhat similar to header files in C). You'll discover how this works while working on the projects of this book.

Type definitions are maintained for most major libraries and are maintained either by the community or the library developers themselves. In most cases, typings are available on DefinitelyTyped, a community-driven repository of type definitions available on GitHub, over at https://github.com/DefinitelyTyped/DefinitelyTyped.

In the following article, you can find the history of DefinitelyTyped, explaining how it came to be and how it has evolved to become so central in the TypeScript ecosystem: https://blog.johnnyreilly.com/2019/10/definitely-typed-movie.html.

This isn't perfect because, sometimes, type definitions fall out of sync with the corresponding library (for example, after a new release) or are flat-out wrong but, most of the time, they definitely improve the developer experience and code quality.

As a matter of fact, type definitions are also useful for JavaScript developers as they provide information about the library APIs that might not even be documented otherwise.

.NET and Java developers will feel at home

TypeScript will feel natural for any Java or .NET developer as it supports many of the concepts that developers with that background should be familiar with.

Career-wise, learning TypeScript is beneficial for any backend developer as more and more code is written using JavaScript and TypeScript nowadays.

TypeScript supports object-oriented programming (OOP) concepts through classes, inheritance, constructors, property accessors, methods, and interfaces. It also supports enums, generics, iterators, generators, modules, decorators (also known as annotations), and many others.

If you only consider the OOP and modularity features of TypeScript, you can easily understand that it makes it much simpler to structure and organize your code base while defining your domain model using familiar concepts.

Also, since it is a superset of JavaScript, it also has great support for functional programming.

Having prior experience with all these concepts certainly gives you an edge to quickly get up to speed with TypeScript.

If you're coming from Java, .NET, or a similar language, do not underestimate the differences between the language(s) you are familiar with and TypeScript; some are quite profound. For example, the this keyword exists both in JavaScript and TypeScript, but it behaves differently in both, which can be very surprising.

That being said, one of the reasons for me (Sébastien) to introduce TypeScript at work a few years back (2016), was to allow our Java development teams to participate in the development and maintenance of frontend applications. At the time, we were developing JavaServer Faces (JSF)-based web applications almost completely in Java, so the introduction of RESTful web services and single page applications was quite a revolution. The fact that we have chosen to use TypeScript really helped the teams to quickly get on board and, in hindsight, it was a really good choice.

Of course, the matter is more complex than this; it isn't because our developers could contribute to the elaboration of frontend application code that they became frontend developers overnight. In our humble opinion, frontend and backend developers usually have a fundamentally different focus during their work. Some have a good feeling for user experience and user interface development and some others just don't.

By now, you have enough background information about JavaScript, TypeScript, how they fit together, and why you have chosen the right language to learn at the right time.

So, let's get started, shall we?

 

What you'll need to install

In order to implement the different projects of this book, and in order to work with TypeScript, you'll need a few tools. In this section, we'll go through the list together to briefly explain what those tools are and why you’re going to need those. Bear in mind that these are merely the strict minimum. In practice, you'll need more than these to build real-world applications.

Text editor

First of all, you'll need a code editor. For this book, we'll be using Visual Studio Code (also known as VS Code or VSCode), an excellent tool created by Microsoft that is free and open source. VS Code provides great editing and debugging support as well as many extensions. It works on Windows, macOS, and Linux. As a bonus, VS Code is also written in TypeScript!

One of the great strengths of VS Code is its extensibility through plugins that are available on the VS Code Marketplace (https://marketplace.visualstudio.com/VSCode). The Marketplace contains thousands of extensions.

As an alternative, you may also use a full-blown Integrated Development Environment (IDE) of your choice, such as WebStorm (https://www.jetbrains.com/webstorm) or IntelliJ (https://www.jetbrains.com/idea), which both closely follow the TypeScript releases and quickly deliver improvements and support for newer versions.

There are, of course, other ones such as Eclipse (https://www.eclipse.org), NetBeans (https://netbeans.org), or Visual Studio (https://visualstudio.microsoft.com) from Microsoft.

In any case, choose well, because the editor is your main weapon and it can have a dramatic impact on your productivity.

Version control system

The second tool that we will use is a version control (VCS or SCM) system. Git (https://git-scm.com) is the de facto standard, so we'll use that. You will mainly use Git to retrieve the book's code samples, but you can also use it to keep track of your own modifications to the projects. We won't cover Git at great length since it is out of the scope of this book, but if you're not familiar with it yet, you should take a look at the official book, which is fantastic to quickly get started. You can find it here: https://git-scm.com/book/en/v2.

Shell

Another tool that we will use heavily with this book is the shell. You can do many things through the command line and it can really have an important impact on your productivity as a developer. With modern shells, you can script many operations and automate a lot of the tasks that you perform many times each day.

On Linux and macOS, using Bash is recommended. There might be some minor differences on macOS because it uses FreeBSD-based utilities, while usually on Linux, you'll have the GNU project ones, but nothing relevant for the purposes of this book.

If you're working in Windows, you can use Git BASH. Git BASH is a Bash shell emulation that is provided along with the Git installer on Windows. There are multiple reasons for this (opinionated) choice, but the main ones are simplicity and homogeneity across platforms. For example, if you need to remove a folder on Windows and Linux, then the commands will differ if you use cmd on one side and bash or sh on the other, while you'll be able to use the exact same command on both Windows and Linux if you're using Bash.

As an alternative on Windows 10 and newer, you may also use Windows Subsystem for Linux (WSL), in which case you'll have access to a standard Bash shell. If you really prefer, you may also use a standard cmd.exe shell or a PowerShell one, but in this book, we'll use Bash for simplicity.

JavaScript runtime

In order to execute TypeScript and many other tools in the JavaScript ecosystem, you'll need a JavaScript runtime. The default option here is Node.js (https://nodejs.org).

Node.js provides multiple things when you install it:

Node.js can actually be used to develop full-blown applications, but in this book, we will mainly use its runtime and package manager. We will only use the Node SDK indirectly.

For the purposes of this book, though, the necessary knowledge of Node.js will be quite limited, as you'll see shortly.

Package manager

The second-to-last tool is also one that you will use most of the time; npm (https://www.npmjs.com) is the official package manager for Node.js. With npm, and through the official npm registry, you will have access to more than 1,000,000 packages, and the numbers keep rising. Hopefully, though, you'll probably need a bit less than that to create your applications!

So why would you need a package manager? If you have experience with any widespread ecosystem, then you'll probably be familiar with a few already: NuGet for .NET, Groovy and Maven for Java, Composer for PHP, and pip for Python. You name it. If not, then here's a short introduction. The basic idea of package management is very straightforward; your projects have dependencies and you need a clean and easy way to get them on your machine, update them to newer releases, and many others.

No matter the size of the project you'll work on in the future, you should consider package management (and actually configuration management in general) as a must. It streamlines your workflow (it's better to have a single, standard way to manage the project), it stabilizes your application if properly used, and can actually help you avoid or detect security issues. For example, npm can detect outdated and/or vulnerable dependencies and warn you. You certainly don't want to have to find/download/extract your dependencies manually.

There are actually three things that we call npm:

  • The command-line interface (CLI)
  • The official npm registry: https://www.npmjs.com
  • The website of the official npm registry

For now, you just need to know that you'll use npm to install dependencies easily and execute scripts. In addition, note that in the npm jargon, the dependencies that npm will manage for you will come in the form of npm packages, which will be downloaded from the official npm registry. Just for completeness, you should also know that there is a popular alternative to the npm CLI called Yarn (https://yarnpkg.com). Yarn was created at Facebook and published as open source in 2016.

TypeScript

Finally, as obvious as it may be, yes, you will also need to install TypeScript.

If you install VS Code, Visual Studio, WebStorm, IntelliJ, or another IDE that supports TypeScript natively, then you already have TypeScript on your machine. Anyway, you'll still need to install it separately from the IDE for reasons that we'll cover in the next sections.

Regardless of how you install it, once TypeScript is installed on your machine, you will get access to the TypeScript compiler, which is called tsc. TypeScript is distributed as an npm package and it can easily be installed using npm. As you will soon see, there are different ways to install npm packages. Some make more or less sense depending on the use case and some others may cause actual issues for development teams.

 

Installing VS Code

In this section, let's install the VS Code together.

Note that we will only cover the installation in Windows and Linux, as we don't own a Mac. Don't worry, though, the procedure is quite similar on macOS.

Windows

Let us assume that you have administrator privileges on your machine, but if you don't, note that you can also download a portable version, as shown in the following steps:

  1. Go to the official website of VS Code and download the installer: https://code.visualstudio.com:

  1. Click on Download for Windows:

  1. Once the installer has been downloaded, click on Run to start it:

  1. Click on Next >.
  2. Make sure to read the license agreement and get it reviewed by your favorite lawyer. Once you're fully aware of what it all means, click on the Next > button:

  1. Change the target location if needed, then click on Next >:

  1. Click on Next >.
  2. On the next screen, make sure to check the Add to PATH (available after restart) option. This is for ease of use only. Then, click on Next > and Install in the next screen.
  3. Once completed, click on Finish:

Congratulations, you're now officially among the cool kids with the code command on their machine.

Windows (shell)

On Windows, you can also easily install VS Code directly from the command line, for example using Chocolatey (https://chocolatey.org).

Linux (GUI)

For Linux, if you're using Ubuntu, you can really easily install VS Code using the native package manager of Ubuntu called Ubuntu Software:

Let's perform the steps as follows:

  1. Open Ubuntu Software.
  2. Then, search for Visual Studio Code and install it:

  1. Once you have found it, click on Install:

Installation should be pretty quick:

  1. Once completed, you should be able to start it:

The following screenshot shows that you are all ready to go:

Let's see how to do the same on Linux.

Linux (shell)

Now, if you're anything like us, at this point you are probably feeling nauseous already. You might not like installing software using a GUI.

Indeed, things have changed, it seems. However, rejoice because if you prefer the command line, then you can still do it (phew!). Microsoft loves open source, so they have great documentation: https://code.visualstudio.com/docs/setup/linux.

For Debian/Ubuntu-based distributions, follow these steps:

  1.  Open the Terminal.
  2. Download the latest .deb package from the official website: https://code.visualstudio.com/docs/?dv=linux64_deb.
  3. Execute the following commands:
    • sudo dpkg -i <file>.deb
    • sudo apt-get install -f

Extensions

In order to install extensions for VS Code, you have two options:

  1. First, you can visit the Visual Studio Marketplace and install extensions from there through the Install links, which will open up in VS Code (that is, vscode:// links):

  1. Once you're on an extension's page, click on Install:

And if all goes well, VS Code should be opened and it should ask whether you would like to install the extension:

This approach is nice because it allows you to easily browse the catalog of extensions. As an alternative, you can use Ctrl + Shift + X (Windows and Linux) in order to install extensions directly from within VS Code:

Here's a small list of nice-to-have extensions (in no particular order). You will not need to have any of these for the purposes of this book, but they'll probably help you, should you decide to install them:

You can find a ton more on the official Marketplace website: https://marketplace.visualstudio.com/vscode.

 

Installing and configuring Git

Now let's install Git, a tool that you will actually use for many years to come.

Windows

Here are the steps to follow in order to install Git on Windows:

  1. Go to the official site for Git and download the binaries: https://gitforwindows.org.
  2. Once downloaded, click on Run. Again, make sure that you don't sell your soul, although this time, we're in safer GNU territory:

  1. On the next screen, make sure to add the Windows Explorer integration (Git Bash Here) and to check the Use a TrueType font in all console windows (your eyes will thank us):

  1. Select your text editor of choice (are you a nano or a vim person? That actually says a lot about you!):

On the next screen, decide how you prefer to work. The default is to Use Git from the Windows Command Prompt, which is a safe choice. The last option is interesting for those among you that would want to use the same *nix tools whether you work in Git BASH, cmd, or another shell:

  1. Choose your preferred transport backend for HTTPS. This is usually relevant for enterprises:

  1. When you reach the following screen, read carefully. This is where many hair loss issues begin and end. The last option is recommended (setting core.autocrlf to false):

  1. Click on Next >:

  1. Click on Next >:

There you go! Now you've got access to Git BASH, your new best friend, right next to PowerShell:

Look how beautiful that prompt looks in the following screenshot:

Once again, let's see how this is done with Linux.

Linux (shell)

On Linux, simply fire up your Terminal and use apt-get, pacman, yum, dpkg, portage, and friends to install Git. Here's how simple the installation looks on Ubuntu when running the sudo apt install git command:

Once you have accepted, apt will install everything you need. After that, the git command will be available for use.

Configuring git

 

Downloading the book samples

Now that you have Git on your machine, you can use the following command to download the latest version of the book's samples on your machine:

git clone --depth 1 -b master https://github.com/PacktPublishing/-Typescript-3.0-Projects---Learn-Typescript-by-Building-Web-Applications typescript-book
You can do it now, as we will use them throughout the book.

Once the command has been executed, you'll find the code samples in the TypeScript book folder.

Code samples are arranged by chapter.

 

Installing Node.js and npm

In this section, we'll explain how to install both Node.js and npm on your machine.

Windows

Go to the official website of Node.js: https://nodejs.org and download the latest LTS (short for Long Term Support) release; you'll find the download links directly on the home page. This is preferred at work, but you may also install the latest and greatest.

For this book, we will be using 8.12.0 LTS, but newer versions should be okay.

Once downloaded, run the installer as follows:

  1. On the first screen, select where to install and click on Next:

On the next screen, make sure that npm package manager is selected so that npm gets installed as well.

  1. Also, check that Add to PATH is selected:

  1. On the next screen, click on Install:

The installation should then get going:

  1. Once completed, click on Finish:

Congratulations, you now have both node and npm on your machine.
In addition, Node.js also comes with a pre-configured shell called Node.js:

If you open up Command Prompt (for example, with cmd.exe), then you should be able to execute node and npm and retrieve their respective versions:

C:\Users\username>node --version
v8.12.0

C:\Users\username>npm
5.8.0

It should also work fine within PowerShell if you prefer that:

PS C:\Users\username>node --version
v8.12.0

PS C:\Users\username>npm --version
5.8.0

The exact version numbers don't matter that much as this evolves all the time, but if you want to be sure to have the exact same behavior, then you can try to match ours.

Git BASH

If you follow our advice and try to use Git BASH, then you might be disappointed at first.

Execute the following command: 

$ node --version

When you do so, you should get back the following error: bash: node: command not found.

Changes to the Windows path are not immediately picked up by Git BASH; for this to happen, sometimes a reboot is necessary (Windows, eh?). If rebooting the operating system doesn't solve the issue, then you can also edit your user profile through the .bash_rc file and modify the path manually. For example, if you've installed Node.js under C:/nodejs, then you can add this to your Bash profile: PATH=$PATH:/c/nodejs. Once done, you should be able to execute both node and npm.

Linux (shell)

On Linux, the installation can easily be done using the Terminal with the following steps:

  1. First of all, open up the Terminal.
  2. Next, install curl as you'll need it to install Node.js: sudo apt install curl
  3. Then, install Node.js from the NodeSource (https://nodesource.com) repository:
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs
  1. You should now have both node and npm installed. Here's a link to the reference installation guide for Debian-and Ubuntu-based distributions: https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions.
nvm (https://github.com/nvm-sh/nvm) is also a popular option to manage multiple node/npm installations.

Let's now see how to update npm.

 

Updating npm

Updating npm is not always as straightforward as it should be, so let us cover this subject, at least for Windows and Linux.

Linux

On Linux, updating npm is very straightforward; just execute the following command:

npm install --global [email protected]

This single command will update npm for you.

Windows

On Windows, updating npm is trickier. The issue on Windows is that npm is installed along with Node.js and if you simply try the same approach as for Linux, the new version of npm that you download will always be shadowed by the one coming with node itself. This is due to the order of the entries in your PATH environment variables.

One workaround consists in changing the order of the path entries. Another one is to avoid installing npm when you install node. This lets you install and upgrade npm separately. That also comes with its hassles, though.

Instead, here's a simple solution, using the npm-windows-upgrade (https://github.com/felixrieseberg/npm-windows-upgrade) utility. To use it, open up a Windows shell (that is, cmd.exe) as administrator then execute the following commands:

  • npm install -g npm-windows-upgrade
  • npm-windows-upgrade

You'll be asked to select the version of npm that you want to install. In the proposed list, select a version that is greater than and equal to 6.4.1. Once the upgrade is completed, you should be able to use the new npm version directly! If you're curious about what changed in the npm cli, check out the official release notes: https://github.com/npm/cli/releases.

Note that there are other solutions such as nvm-windows (https://github.com/coreybutler/nvm-windows) that we won't be covering here.

 

Installing TypeScript

TypeScript is distributed as an npm package, and thus, it can easily be installed using npm.

Here's how to install TypeScript globally:

npm install --global typescript

If all goes well, you should be able to execute the compiler from anywhere:

$ tsc --version
Version 3.1.1

As you can see from the preceding command, we could invoke the compiler without prefixing it by its path.

An alternative to the typescript package is the npx command, which comes along with npm. npx allows you to use commands easily without having to go through the hassle of installing packages globally. Note that npx also works for locally installed packages, but we’ll learn about that later on!

Let's now start using TypeScript!

 

Hello world with TypeScript

Now that you have all the tools at your disposal, let's write the ceremonial Hello World in TypeScript.

Creating the project

Open your favorite Terminal (again, we will assume Bash here). Create a new folder called hello-world:

$ mkdir hello-world

After the previous command, you can go into the newly created folder:

$ cd hello-world

Now open VS Code in the current folder using the code . command.

Hello (Type/Java)Script!

So, TypeScript is a superset of JavaScript, right? Let's see what that actually means by following these steps:

  1. Create a new file called hello-world.ts:
The .ts file extension stands for TypeScript.

You can do it from within VS Code:

As you can see, VS Code directly recognizes TypeScript files:

  1. Now add the following code to your newly created file:
var hello = "Hello world";

function say(something) {
console.log(something);
}

say(hello);

Now let's do a silly thing: let's ask Node (our JavaScript interpreter) to execute our TypeScript code:

$ node hello-world.ts 

The output will be as follows:

That worked? Well, as you have probably guessed, this first example only contains JavaScript, which is why node doesn't have any issue.

 

Compiling manually using the TypeScript compiler

Now let’s try to use tsc (the TypeScript compiler) to manually compile our code.
Go back to the Terminal and run tsc:

As you can see, there are many options. You can list all the available options using tsc --all. We'll discover some of those as we go about building cool applications together but, for now, let's focus on the task at hand: compiling a single file. You can do this by executing tsc hello-world.ts.

If all goes well, you should see nothing. But TypeScript should have transpiled your code to JavaScript.

By convention, TypeScript generates a .js file with the same name as the input file, right next to it. If you list the directory contents, you should see the newly added file:

$ ls
total 2.0K
drwxr-xr-x 1 dsebastien 197121 0 Sep 25 15:42 .
drwxr-xr-x 1 dsebastien 197121 0 Sep 25 14:07 ..
drwxr-xr-x 1 dsebastien 197121 0 Sep 25 14:16 .vscode
-rw-r--r-- 1 dsebastien 197121 100 Sep 25 15:42 hello-world.js <-----
-rw-r--r-- 1 dsebastien 197121 104 Sep 25 15:29 hello-world.ts

Let's see what TypeScript has generated for us:

var hello = "Hello world";
function say(something) {
console.log(something);
}
say(hello);

This is, apart from whitespace, the exact same code. Captain Obvious again here, but indeed, since we have given JavaScript code as input to TypeScript's compiler, it didn't have much to do for us. This was just a tease; now let's make use of the TypeScript type system!

 

Variables declaration

In the previous code sample, we used the familiar var keyword of JavaScript to declare our variable.

Before we code anything else together, you really need to know that var is a keyword that you should forget about and never use again.

Why? The issue is that var does not support block scope. Instead, variables declared with var are function-scoped and any variable declarations in a block will get hoisted to the surrounding function.

Hoisting is a weird JavaScript concept. In JavaScript, variable declarations (and declarations in general) are treated first, before anything else is executed. This means that declaring a variable anywhere is exactly the same as declaring it at the top. This also means that a variable can be used before it is declared, which is counter-intuitive, to say the least.

This might sound unclear, so let us give you an example:

var a = 12;
var result = a + b;
var b = 30;
console.log("Result: ",result);

The previous code is a perfectly valid JavaScript code (but is certainly not recommended).

Up until ES5, var was the only way to declare variables, but this has changed with ES2015, which has introduced two new keywords: let and const. Both of these keywords do support block scope.

The let keyword is the safer alternative to var, while const allows you to define constants.

We are putting constants between quotes because the const keyword does not make objects immutable; it only ensures that the variable cannot be reassigned, but the contents of the object it points to can be modified.

Here is the recommended order of preference: const > let > var.

Why? As you'll see throughout the book, defensive programming has many merits and can help you write better and safer code. While programming defensively, you'll notice that immutability has many benefits, for example, to avoid side effects and surprises.

In practice, even if const does not guarantee immutability, it is still a step in the right direction and it clearly conveys the intent of your code, which is very important. Hence, our recommendation is to use const whenever possible and to only use let when you need to be able to assign different values.

Basic TypeScript types

Before we go on, let's see what basic types are supported by TypeScript:

  • boolean: true or false.
  • number: Floating point values. Those can be expressed in hexadecimal, decimal, binary, and octal forms.
  • string: can be delimited by single quotes ('), double quotes ("), or back-ticks (`) to define template literals (also known as template strings).

Here are some examples of numbers:

  • let decimal: number = 42
  • let hexadecimal: number = 0x42
  • let binary: number = 0b101010
  • let octal: number = 0o52

Here are some string examples:

  • let hello: string = 'Hello'
  • let world: string = "World" // same as above
  • let cool: string = `${hello} ${world}!`

Template strings are very useful—they make it really easy to embed expressions. In the preceding example, we've just included another string, but in a template string expression, you could also invoke functions, perform calculations, and so on. Template strings usually help improve code readability. Note that string templates are actually a feature of ES2015 (that TypeScript supports by default).

You can also define multiline template literals!

TypeScript also supports other basic types that we will cover later on: arrays, tuples, enums, any, void, null, undefined, never, and object.

A tiny bit of type safety can't hurt

To wrap this chapter up, let's write another example. This time, we will write an unsafe program and then we will see how we can make it safer using TypeScript.

Our program will be a simple calculator. For the sake of the example, our calculator will only be able to multiply values together, but don't hesitate to extend the example to include other operations as well.

Create a new file and call it calculator.ts. In that file, add the following code:

function multiply(a, b) {
const result = a * b;
console.log("The multiplication of "+a+"*"+b+" equals to :
"+result);
return result;
}

multiply(1, 2);
multiply(2,2);
multiply(-10,10);
//multiply('foo', "bar");

We've used const this time because the calculation result should never be changed.

If you now compile and execute this calculator (using tsc calculator.ts, remember?), you'll see the results of our calls to the multiply function.

Everything seems fine so far, as shown here:

$ node calculator-unsafe.js
The multiplication of 1*2 equals to : 2
The multiplication of 2*2 equals to : 4
The multiplication of -10*10 equals to : -100

However, that code isn't very safe. What if you uncomment the last line? Do you think it makes sense to multiply strings together when doing calculations?

Now, indeed, the output is more problematic:

$ node calculator-safer.js
The multiplication of 1*2 equals to : 2
The multiplication of 2*2 equals to : 4
The multiplication of -10*10 equals to : -100
The multiplication of foo*bar equals to : NaN

Is this a behavior that you had intended? Probably not! The main problem that you have here, since that code is actually again mostly JavaScript, is one of expressiveness; you cannot easily/clearly state which types you expect as an input of the function. This is really unsafe because you could pass just about anything to your function.

You can, of course, write safer code in JavaScript, but at the expense of readability and conciseness.

Now, let's see how TypeScript can help. Actually, without you knowing, it already does!

Try to add this line to the code: multiply(1). This lacks an expected parameter. In pure JavaScript code, this would be alright, but TypeScript's compiler does complain now: TS2554: Expected 2 arguments, but got 1.

Let's go further now. Adapt the code as follows to specify the types that you expect:

function multiply(a: number, b: number) {
const result: number = a * b;
console.log(`The multiplication of ${a}*${b} equals to
${result}`);
return result;
}

multiply(1, 2);
multiply(2,2);
multiply(-10,10);
multiply("foo", 'bar');

We now have changed the console.log call to make use of a template string. Doesn't this make the code more readable? Also, take a look at the generated JavaScript code for this line: console.log("The multiplication of " + a + "*" + b + " equals to " + result);. As you can see, TypeScript has replaced our template string, making the code compatible with ES3.

As you can see, we can easily specify variable types using the : type notation, including for function parameters.

If you try to compile the program again, you'll see that TypeScript now helps us to avoid more mistakes:

$ tsc calculator-safer.ts
calculator.ts:10:10 - error TS2345: Argument of type '"foo"' is not assignable to parameter of type 'number'.
10 multiply("foo", "bar");
~~~~~

Isn't this wonderful? But wait, there's so much more yet to discover!

 

Summary

In this chapter, you have discovered the current frontend development landscape and seen why/where TypeScript comes into the picture.

We have illustrated the issues with vanilla JavaScript and shown how TypeScript can help to improve code quality.

We have presented the different tools that you'll use on a day-to-day basis, including how to install them. Now, you know about VS Code, Node.js, npm, Git, and Git BASH. There are more tools that you should add to your toolbox, but we will discover them together later on.

Finally, you have written your first pieces of code using TypeScript, compiled them using tsc, and discovered how to improve your code using basic types and safer variable declarations.

In the next chapter, we'll create our first real application. It won't take over the world (yet), but it will certainly help you to learn more about TypeScript's basic features!

 

Further reading about ECMAScript

About the Authors

  • Sebastien Dubois

    Sebastien Dubois is a passionate software craftsman and FOSS contributor with many years of experience as a senior developer and technical team leader. He is an entrepreneur, IT consultant/coach, and owner of DeveloPassion, a Belgian IT firm. Over the years, Sébastien has worked on backend systems, web applications, architecture, and IT security for various organizations. He has used different programming languages, which gives him a broad perspective on modern software development. He has also been using, teaching, and advocating TypeScript since 2015. You can find him on Twitter as @dSebastien, on Medium as @dSebastien, or on his personal blog: dsebastien.

    Browse publications by this author
  • Alexis Georges

    Alexis Georges is a developer who is passionate about software development, but also about everything related to IT: open source, system administration, respect for privacy, and many others. During his studies in programming and networking, he learned the basics of programming and system administration. Alexis has some experience in JavaScript, PHP, Java, C, and (obviously) TypeScript. He discovered the TypeScript programming language when he began his career as a software engineer in Sebastien's team. Later, he participated in the migration of the Stark framework from AngularJS to Angular. You can find him on Twitter as @Super_ITMan and on his blog: SuperITMan.

    Browse publications by this author

Latest Reviews

(1 reviews total)
It is way to early to provide a comment about this since I just purchased the book and I've not yet completed reading it.

Recommended For You

React Projects

Build cross-platform applications of varying complexity for the web, mobile, and VR devices using React tooling

By Roy Derks
The JavaScript Workshop

Cut through the noise and get real results with a step-by-step approach to beginner JavaScript development

By Joseph Labrecque and 7 more
Hands-On Software Architecture with C# 8 and .NET Core 3

Design scalable and high-performance enterprise applications using the latest features of C# 8 and .NET Core 3

By Francesco Abbruzzese and 1 more
Professional JavaScript

Develop your JavaScript programming skills by learning strategies and techniques commonly used in modern full-stack application development

By Hugo Di Francesco and 3 more