What is TypeScript and why should you use it?

What's TypeScript? It's a powerful tool for frontend & backend developers. It promotes better code quality and protects against common JavaScript mistakes.
Published
August 18, 2022
Updated
March 5, 2024
Category

Guides

The TypeScript programming language has many advantages over JavaScript for developers. The additional functionality TypeScript provides makes it possible for you to build more complex interactive applications and websites with fewer bugs.

TypeScript also has a big ecosystem of developer tools that provide inline documentation and live code checking that makes it easier to catch coding mistakes while you're working. 

This article explains what TypeScript is and its relation to JavaScript, and provides resources to help you get started building frontend and backend applications.

What is TypeScript?

TypeScript is a programming language that adds extra functionality to JavaScript. 

JavaScript was never intended to drive complex frontend and backend applications. It was initially designed to add simple interactivity to websites; for example, to make clicky buttons and animate drop-down menus.

Despite this, JavaScript became popular with developers who found ways to use it way beyond this use case, which led to problems: the language was too forgiving and made it very easy to make programming mistakes or misuse features that would later break an application, and JavaScript lacked many features of other languages. TypeScript was developed specifically to address these issues while remaining compatible with existing JavaScript environments.

TypeScript is a statically typed language and a superset of JavaScript that builds on top of JavaScript’s existing syntax and functionality. This means that you can use JavaScript in your TypeScript code, but you can't use TypeScript in your JavaScript code as code written in TypeScript uses features and syntax not present in JavaScript. 

TypeScript must be compiled (transpiled is another term as it isn’t converting to a low-level language) to JavaScript to run in web browsers and in environments like Node.js. Once TypeScript code is compiled to JavaScript, the resulting JavaScript code isn’t supposed to be edited directly.

The workflow for building TypeScript apps is to write them in TypeScript, compile them to JavaScript, and then deploy them. While this extra step may seem like unnecessary added complexity, it's there for a very good reason: TypeScript would not have caught on if it were a completely new language, but  because it compiles to JavaScript so that it can run on existing systems, it has been widely adopted.

The file extension for TypeScript is .ts. Below is an example file named index.ts with some basic TypeScript code:

Notice that while the syntax is very similar to JavaScript, there's something different visible in this example: the message variable is followed by a colon (:) and its type — in this case TypeScript — is letting us specify that the message must be a string, and cannot take a value of a different type.

Top features and advantages of TypeScript for developers

TypeScript is named as such because its primary feature is introducing type safety to JavaScript. In the above example, a string type is enforced for the message variable, so no numerical or other type of value can be used there. This may seem limiting, but it's actually a benefit to developers.

Type safety and compile-time checks reduce the ways you can make programming mistakes

Consider this scenario: You are taking the values from two HTML text inputs and you want to add them. JavaScript reads these values as strings (it's a text box!). What you wind up with is this:

This code will run without any warnings or errors, with the values from the text boxes treated as strings, which means they are concatenated instead of being added using arithmetic operations, leading to the unintended result of "25" instead of the number 7. This could be really bad if you're building a commerce tool and want to add some monetary values together — you'd overcharge your customer!

This demonstrates why type safety is important. Below, the type of the variables being added is enforced by adding a type to them:

If you try to compile and run this code, it won't — you'll get an error instead:

Type 'string' is not assignable to type 'number'.

This tells you that you've mistakenly tried to assign a string value to a numerical variable, so that you can fix it — for example, by explicitly converting the string to a number. By preventing you from even compiling and running your code if there are type errors in it, TypeScript makes your app easier to debug, and more reliable for your users.

You don't have to specify a variable’s type when working in TypeScript (though you generally should): type inference lets you declare and use variables without a specified type, and TypeScript will infer the type based on the value and usage. This is useful when bringing in untyped JavaScript code for use in TypeScript projects.

If you want to play around with this for yourself, the TypeScript Playground lets you write and test TypeScript code right in your browser, without needing to compile.

Custom types, classes, and interfaces keep your data consistent

TypeScript extends JavaScript’s support for object-oriented programming with support for your own custom types, as well as improvements to classes, interfaces, and inheritance.

  • Building your own object types and interfaces lets you model your data in TypeScript to ensure that your data is processed and stored properly.

  • Classes and inheritance enable clean code and DRY principles, keeping your codebase much more organized than traditional JavaScript allows.

Enums and literal types make your code easier to understand

Enums make your code more readable and easier to understand by giving names to values that may otherwise be ambiguous.

For example, suppose you’re storing the status of an order in your database as a numerical value to save space and make it faster to search. Instead of "pending,", "paid,", and "shipped,", you might store those values as numbers 0, 1, and 2, respectively.

The side effect of this is that your code would become confusing as the numbers don't really describe much on their own. You might forget which number corresponds to which status, and use the wrong one. Enums offer a convenient solution:

In the above enum, "pending" has the value 0 (enums, like other indexes in programming, start counting the position of items at zero), "paid" the value of 1, and "shipped" the value of 2. When using the enum, you refer to its values by name, and the index value will be returned:

console.log(OrderStatus.paid); // Will output 1

Literal types and unions enforce specific values for variables. For example, you may have a function that only expects to receive the value "cat" or "dog":

If your code passes values other than "cat" or "dog" to this function, an error will be raised. This helps make sure more problems are caught during development: You can write functions that expect certain input knowing that if a bug is introduced that passes them an unexpected value, your application will not compile.

How to install TypeScript and use the TypeScript compiler

TypeScript code needs to get compiled into JavaScript so that it can be run in web browsers and Node.js, and for that, you need to install the TypeScript compiler.

You can install TypeScript globally using the following npm command.

npm install -g typescript

Once it’s installed, you can run the tsc TypeScript compile command from anywhere in your terminal using npx:

tsc index.ts

The above command will compile the TypeScript file index.ts and output a compiled JavaScript file named index.js.

How to write apps in TypeScript

TypeScript really shines when building complex, multi-page applications, and websites. Most developers won't use it for basic things like adding interactivity to single web pages, but will use it to build large applications with React or Angular.

Many developers use code editors that support TypeScript integration so that they can take advantage of code completion, inline documentation, and error highlighting to streamline their development and debugging processes.

Can I use my existing JavaScript code?

Yes! TypeScript is backward compatible with JavaScript. You can bring in your old JavaScript code and continue using it in your TypeScript projects, and refactor it over time to leverage new TypeScript functionality.

Building front ends with TypeScript for the browser

React is a library that assists you in building user interfaces for your front ends. It provides the foundations for you to build reusable components, modularizing and streamlining your app development. It also lets you create dynamic pages that the user can interact with by, showing, hiding, moving, and changing the appearance of on-screen content. React apps can be written in TypeScript: this combination is a popular and powerful toolchain for frontend developers.

Angular is a full framework that uses TypeScript to build its components. It takes things further than React: iIn addition to providing tools for building user interfaces, it provides the framework for a whole application. Angular’s opinionated approach allows developers to build faster, provided that their application's concept fits within Angular's architecture.

Both React and Angular can be used to build TypeScript apps for Ionic and Electron. Ionic lets you build mobile apps for iOS and Android using TypeScript, and Electron lets you embed your web apps in desktop applications for Windows, Linux, and MacOS.

Deploying TypeScript backends to the server

TypeScript isn't limited to building frontend applications. It can also be used with Node.js to develop backend services and command line applications. 

You can also use TypeScript with the Fastify web framework, or use a TypeScript specific framework like Nest to build type-safe APIs.

TypeScript and GraphQL

TypeScript and GraphQL help keep the data in your front- and back ends consistent.

GraphQL is a query language for searching and retrieving data from APIs. Like TypeScript, it is typed, so it provides structured and consistent data. By utilizing services that support GraphQL and implementing it in your own back ends, and matching its types with those in your TypeScript code, you can greatly improve the quality of your applications by ensuring that all data that is modeled on your backend services is correctly reflected in your frontend interfaces, and that all data collected on your frontends is correctly stored when it is uploaded.

If you are using Contentful to manage your composable content, our community members have created apps and tools that help generate type declarations for your content types and sync TypeScript with your content model.

What's the best way to learn TypeScript?

TypeScript comes with tons of useful features for developers, and learning and implementing them all at once might seem overwhelming. But, due to its support for existing JavaScript code, you don't have to implement every TypeScript feature in one shot. 

One approach is to learn about a few TypeScript features, and then apply them to your JavaScript code, function-by-function, and once that's done, pick another set of TypeScript concepts to implement and repeat. This helps to migrate your codebase to TypeScript with minimal effort and helps you dive deeper into the concepts.

The TypeScript Handbook is a great place to learn about building apps in TypeScript. It explains the concepts well and contains relevant examples. The handbook is also regularly updated with new information about what TypeScript is and does.

There are also tutorials available that will help you with migrating your JavaScript project to TypeScript or help you learn about DOM manipulation in TypeScript.

If you're looking for your next TypeScript project, why don't you create an app for your Contentful space with the Contentful App Framework? Happy type checking!

Start building

Use your favorite tech stack, language, and framework of your choice.

About the authors

Don't miss the latest

Get updates in your inbox
Discover new insights from the Contentful developer community each month.
add-circle arrow-right remove style-two-pin-marker subtract-circle remove