← Impulso Blog

How to use TypeScript and why it’s worth using

TypeScript can be a big help, but you need to understand how it works. Here are some tips on how to use it and a look at its advantages.

Official TypeScript logo.

Editorial translation by Impulso.

There’s no better way to start than with a little history of TypeScript (TS), what it does, and why this incredibly useful tool exists. That’ll give you some context for what TypeScript is and what problem it was created to solve. Then we’ll dive right into your first project and see how each part of the configuration works.

Background

TypeScript began as an internal Microsoft project in 2008 and was released to the public on October 1, 2010, with the basic idea of bringing static typing to JavaScript code. The main focus was on building larger applications, where JavaScript doesn’t scale efficiently (we’ll come back to that).

Contrary to what some people think, TS isn’t considered a language in its own right. It’s a superset of JavaScript. But that didn’t clear much up, did it? Let me give you a more practical example. TypeScript includes everything JavaScript already has and extends it further. So all JavaScript code is valid TypeScript code, but the reverse isn’t true, by definition.

Uses

Unlike other languages, TS was created to extend JavaScript rather than replace it, just as another tool called Flow had done before. That’s why many people say TypeScript itself isn’t a language but a type system implemented on top of JavaScript.

But unlike other type systems that came before it (yes, TS is neither the first nor the second), TypeScript’s type system is considered Turing-complete, which means we can solve problems of any complexity using only the constructs it provides. In fact, there are entire projects, including games, parsers, and even small applications, built entirely with TypeScript’s type system.

Of course, since the type system has no interface, devs had to find creative ways to show users the output. One example is TDungeon, a text-based RPG built entirely in the TS type system.

Image illustrating TypeScript.

Growth

One interesting fact is that one of TS’s main designers and developers is a Danish software engineer named Anders Hejlsberg. He’s also the lead designer of C# and created languages like Delphi and Turbo Pascal. That’s why, at first glance, TS code looks a lot like C# code, especially in how it’s structured.

Today, TS is one of the most widely used tools in the world and a favorite among devs because, among many other things, it helps you stay sane on very large projects.

Why TypeScript?

Now that we know where TS came from, let’s look at why it exists.

Over the course of my career, I’ve worked on small and large projects using JavaScript, and the language itself isn’t the problem. In fact, many of those projects were only possible because JavaScript is much simpler than other languages. Scaling those applications can be a problem, though, as a direct consequence of JavaScript’s dynamic typing. Let’s see what that looks like in practice. Imagine you have this application using Express with Node.js:

Image illustrating the use of Express with Node.js.

In this example, we have just three middleware functions, and we can already see how hard it is to tell what’s in res.locals. In larger applications, it’s easy to end up with more than 30 middleware functions per route (it’s bad practice, but it happens). In cases like that, it’s impossible to know what’s in this variable, especially if the middleware functions are defined in separate files.

Another interesting example is when we need to make sure we’re using a particular data type. Let’s say we have the following code:

Example using setInterval and setTimeout to create an interval and a timeout and store their identifiers.

Functions

In JavaScript, we have two functions for canceling timeouts and intervals, clearInterval and clearTimeout, but each can only take the corresponding kind of ID. In other words, if we try to use clearInterval (timeoutId), nothing will happen. That’s where TypeScript shines, with something like this: TypeScript example distinguishing interval and timeout identifier types and flagging the wrong type.

See what I mean? At the end of the day, TypeScript’s goal is summed up by its own slogan: "JavaScript that scales." It lets you build huge applications with lots of modules and plenty of complexity without losing track of each variable’s type. That’s especially useful when you’re working on a team, since knowledge of the application is spread across many people.

Other advantages

Another important point is that TypeScript drastically reduces what we call the bus factor, a way of describing how many people can be out of your project before it becomes unsustainable. It’s usually closely tied to the people who joined at the start and, as a result, know the business rules and the codebase inside out. But if they leave your company, the project is done for, because nobody else knows anything. With TypeScript, you can at least keep a better handle on the codebase, making it much easier to pass that knowledge on.

TypeScript also makes it easier to debug directly, meaning you don’t even have to run the code or a test suite to know that something’s wrong. If your types are correct, you can solve complex problems without running the code even once. It also helps with documentation and application architecture.

The TypeScript compiler can do plenty of other things besides checking types. One way to use TS is to break large projects into smaller ones and bring them together using a module system.

All right, have I convinced you that TypeScript is worth it? Let’s learn how to install it and make the most of what it offers.

Setting up your environment

TypeScript can run in any environment, and you can use any editor to create a TS file. After all, most editors now support TypeScript type analysis. My personal recommendation, though, is VSCode because it was originally built to work with TS. It supports all of TypeScript’s features out of the box and even comes with its own bundled version in case you need to analyze a file and don’t have TypeScript installed on your machine yet.

NPM packages and compilation

TypeScript is written in TypeScript (how poetic) and published to NPM as a package. To start using it in your first project, just create a new folder and run npm init -y, then install the TypeScript package with npm install -D typescript. We can also install all the Node.js type definitions so TS knows about the environment we’re running in. To do that, use the command npm install -D @types/node_._

When it comes to compilation, though, the process is different.

When you install TypeScript, you’ll get access to a binary called tsc, the TypeScript Compiler. It transpiles TypeScript to JavaScript, since no environment (neither the browser nor Node.js) runs TypeScript natively.

First, we need to initialize TypeScript in the folder. We can do that with npx tsc --init. You’ll now see a tsconfig.json file at the root, and that’s what we’ll focus on.

Now create a file called sum.ts and put this code in it:

An asynchronous sum function accepts two numbers, returns a Promise and throws an error for invalid arguments.

Now run npx tsc ./sum.ts. That should give you a sum.js file in the same folder. Try running it with node sum.js and see what you get!

TSconfig

The TypeScript configuration file is called TS Config, and it’s the heart of the whole project. The presence of tsconfig.json tells TypeScript that this is the root of a TS repository. That’s where it looks for all the settings it needs to compile the project. As we’re used to with Node, when we invoke the TS compiler, tsc, without any arguments, it looks for the nearest tsconfig.json file and reads its options. You can also specify exactly which configuration file to use with tsc -p .

You can also override any properties in tsconfig.json from the command line by passing the options directly. That’s handy when you need to change something for a particular build.

All right, I want to walk you through the main TSConfig settings and explain what each one does! First, though, we need to understand how the file is structured.

Basic fields

It starts with what are called root fields, the keys that tell TS which files to take into account:

Files

A list of filenames to include in the program you’re compiling, for example:

The files field explicitly lists core.ts, sys.ts and types.ts for compilation.

Extends

This is one of the most powerful features of tsconfig. It lets you extend other configuration files. TS even provides base files that come ready to use. You can extend them directly from the repository with extends: "@tsconfig/node16/tsconfig.json".

This feature also comes in handy when you’re working with monorepos that contain many projects. You can keep the base file at the root and customize the configuration for each project. Any extra settings are treated as changes to the base configuration. If an option exists in the base file and is overridden in the second file, the later setting wins.

TypeScript example defining options in a base configuration and extending it in another file that specifies inputs.

Include and Exclude

Like files, include and exclude control which files you include in the project. The difference is that these keys accept globs, that is, regular expressions that match one or more files. They’re handy when you can’t list the files directly with files_._ A tsconfig excerpt using include patterns for files under src and tests.

Compiler options

This is the most important field in the file. It’s where you define how the TypeScript compiler behaves. There are lots of options, so I’ll cover a few that I think are most important.

  • exactOptionalPropertyTypes: This option makes optional interface fields like { color?: 'blue' | 'red' } stricter. This code would resolve to color: 'blue' | 'red' | undefined. With the option enabled, undefined is no longer an option.
  • noImplicitAny: This is one of the more controversial TS options. The idea is to stop TypeScript from automatically inferring any, the scourge of all TS types. With a function like const f = (s) => s, TS will complain that s is any. I strongly recommend turning this option on because it’s the most efficient way to keep only the instances of any you actually want in your code.
  • noImplicitReturns: This is another noImplicit option I strongly recommend enabling. It ensures that every path you can take returns a value.
  • module: Changes how TS loads modules. You generally won’t change this option, but each setting behaves differently and changes the resulting file.
  • paths: An interesting option that lets you create your own import maps, telling TypeScript how to load a file and letting you set up something like this, for example:

In compilerOptions, the jquery alias points to the distribution under node_modules/jquery/dist/jquery.

It also lets you write import 'jquery' directly, which is equivalent to using something like this:

TypeScript configuration setting baseUrl to src and mapping the @tests/* alias to tests/*.

See you next time!

All right, now that we’ve gone over what you knew and didn’t know about TypeScript, make the most of its advantages and put it into practice to keep learning. For that, I recommend joining a community. It’s the best way to stay in touch with other devs and keep learning. So if you haven’t checked out the community Impulso runs on Discord and WhatsApp, now’s a great time!

About the author

Lucas Santos is an Impulser Expert. He’s also a software engineer and has been creating bugs since 2011. He’s passionate about technology, knowledge, and content. Follow him here.

In fact, Lucas has just launched his complete TypeScript training course! "Fomação TS" is available on the official course website with an exclusive pre-launch discount.

Related articles