What is TypeScript and why should you use it?

What is typescript
Published
August 18, 2022
Category

Developers

I've been learning and using TypeScript for the past year for various projects, and I have been enjoying it. TypeScript provides a great developer experience, and I believe that it has increased my productivity. I don't have to manually check for errors every time a change gets made, and the inline documentation helps me ship faster. In this article, I will give you an overview of TypeScript, share some of its features, and help you get started.

Before learning about TypeScript, let's take a step back and revisit JavaScript. Since the earliest days of the World Wide Web, JavaScript has been used to make websites interactive – handle mouse and keyboard events, validate forms, and so on. With time, the language evolved. You can now use JavaScript to build websites and apps for any platform. It can be used to code both the frontend and backend of your website/app. You can build cross-platform apps using React Native and desktop apps with Electron, and you can even use JavaScript for your next IoT project!

With these extensive use cases, the complexity in the codebase increased. For smaller projects, using JavaScript is still fine. However, for larger projects, it became difficult to debug the code and catch errors.

What's the difference between TypeScript and JavaScript?

TypeScript is a superset of JavaScript. It means that TypeScript provides all the features and functionalities of JavaScript with some added features. TypeScript compiles to JavaScript, which the browser understands. TypeScript provides "type safety" (hence the name!) to JavaScript. It was created by Microsoft and is open source. If you’re interested in contributing or just going through the source code, you can find the repository on GitHub.

To understand type safety, consider an example where you define a variable name. In JavaScript, you would use a similar code as below:

Since this is a variable name and we haven't defined its type, this variable can have any value. It doesn't matter if it's a string, number, boolean, or object. Hence, the below code will execute without errors:

Using TypeScript, you can define the type string for the variable name, as below:

If you change its value to any other type, the compiler returns an error. Type safety saves a lot of debugging time and helps in keeping the code consistent.

Features of TypeScript

TypeScript extends JavaScript and improves the developer experience. It enables developers to add type safety to their projects. Moreover, TypeScript provides various other features, like interfaces, type aliases, abstract classes, function overloading, tuple, generics, etc. Explaining all the features is out of the scope of this article. However, I will present two that I find useful.

Interface

You receive an object when you call any Contentful API. This object response contains the necessary data that you need. Similar to the Contentful API, other APIs also send an object as a response.

Interfaces get used to ensure that the object contains the required data with the correct data type. This object can be a response or request body or parameters for a function.

An interface has the following syntax:

Using the above syntax, we can create an interface Profile with the properties name and social.

The above interface can be used as follow:

The above is a simple example of interfaces. There are various other functionalities that interfaces provide. You can set optional properties, extend interfaces to add new properties, and more. To learn more about interfaces, refer to the TypeScript documentation.

Literal Types

Another feature that I find useful is Literal Types. Though, by themselves, they're not so useful. But one can combine them into unions, which makes the Literal Types useful.

The following example demonstrates the syntax of Literal Types.

Here, the variable social has the type "twitter." However, this isn't useful on its own.

In the above function, the second parameter can only take values that have the type of either "Alice" or "Bob." This helps us in writing functions that only accept a certain set of known values. They can do much more with Literal Types. Read the official documentation to learn more.

How to use TypeScript?

Now that you have a basic understanding of what TypeScript is, in this section, you will learn how to use TypeScript.

Browsers don't understand TypeScript. They understand JavaScript code. Hence, the TypeScript code needs to get compiled into JavaScript, and for that, you need the TypeScript compiler.

You can install TypeScript globally using the following npm command. The global installation allows you to run the tsc command anywhere from your terminal.

npm install -g typescript

Once you have installed TypeScript, create an index.ts file and add the following code:

The above code declares a variable message and creates a function that logs the message to the console. To run this code, you have to compile it to JavaScript. Run the following command:

You'll observe that the compiler creates an index.js file with the compiled code.

The TypeScript compiler is flexible and allows you to configure options like the target JavaScript version. At the time of writing this article, the default target is es3.

To configure the compiler options, you can either pass them with the CLI command or create a tsconfig.json. You can learn more about the various configuration options on the TSConfig Reference documentation page.

If you want to use TypeScript in your next Contentful project, we released contentful.js v10 in Beta with enhanced TypeScript support. Check out the changelog and let us know what you think!

Advantages of using TypeScript

TypeScript extends JavaScript, providing a better developer experience. The benefits of using TypeScript over JavaScript include:

  • Static typing – TypeScript comes with optional static typing and a type inference system, which means that a variable, declared with no type may be inferred by TypeScript based on its value.

  • Object oriented programming – TypeScript supports object-oriented programming concepts like classes, inheritance, etc.

  • Compile time checks – JavaScript is an interpreted programming language. There is no compilation involved. Hence, the errors get caught during the runtime. Since TypeScript compiles into JavaScript, errors get reported during the compile time rather than the runtime.

  • Code editor support – IDEs or code editors like VS Code support autocomplete for a TypeScript codebase. They also provide inline documentation and highlight the errors.

  • Use existing packages – You might want to use an npm package that is written in JavaScript. Since TypeScript is a superset of JavaScript, you can import and use that package. Moreover, the TypeScript community creates and maintains type definitions for popular packages that can be utilized in your project. You can learn more about it here.

What's the best way to learn TypeScript?

TypeScript comes with tons of features, and learning and implementing them all together might get overwhelming. I started learning TypeScript by refactoring my JavaScript codebase to TypeScript one line at a time. This helped me to migrate my codebase to TypeScript with minimal effort and helped me dive deeper into the concepts.

The TypeScript Handbook is a great place to learn about TypeScript. It explains the concepts well and contains relevant examples. The handbook is also regularly updated with new features.

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.

The Contentful community members have also created apps and tools that can help generate type declarations for your content types and sync TypeScript with your content model.

If you're looking for your next TypeScript project, why don't you create an app for your Contentful space with App Framework? The boilerplate is available in TypeScript, where you can learn or brush up your TypeScript knowledge. Happy type checking!

Get started!

Start building with a free Contentful account, no credit card required.

About the author

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