What is TypeScript and why should you use it? (2024)

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

What is TypeScript and why should you use it? (1)

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!

What is TypeScript and why should you use it? (2)

Subscribe for updates

Build better digital experiences with Contentful updates direct to your inbox.

Front endBack end

What is TypeScript and why should you use it? (2024)

FAQs

What is TypeScript and why should you use it? ›

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.

Why do we use this in TypeScript? ›

TypeScript Declaring this in a Function, where 'this' in TypeScript refers to an object's current instance in a function, granting access to its properties and methods.

Why use any TypeScript? ›

The any type is an escape hatch—it allows you to effectively turn off Typescript's type checking. Sometimes, there just isn't a good way to tell Typescript what you are doing, so you use any to work around that.

Why is everyone using TypeScript? ›

Without the extra features, TypeScript adds to JavaScript, it's easy for bugs, errors, and issues to creep into production code and cause problems for both the application and its users. But, thanks to TypeScript's static types, we can catch these issues in development and prevent the issues from impacting users.

Why learning TypeScript is important? ›

TypeScript is an invaluable tool for modern front-end development. Its static typing system significantly improves code reliability, maintainability, and developer experience, especially in large-scale projects.

What is TypeScript good for? ›

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.

Why do we need TypeScript instead of JavaScript? ›

TypeScript offers several advantages over JavaScript, such as static typing, interfaces, enums, and advanced tooling support. These features can lead to fewer bugs, improved code quality, better IDE support, and enhanced developer productivity, especially in larger projects with complex codebases.

Why is TypeScript so hard to use? ›

Understanding the Complexity of TypeScript

The primary challenge in learning TypeScript lies in its departure from the dynamic nature of JavaScript. Programmers accustomed to JavaScript's flexible type system may find the strict type requirements of TypeScript initially overwhelming.

Why avoid using any in TypeScript? ›

❌ Don't use any as a type unless you are in the process of migrating a JavaScript project to TypeScript. The compiler effectively treats any as “please turn off type checking for this thing”. It is similar to putting an @ts-ignore comment around every usage of the variable.

Why TypeScript is getting popular? ›

There are a few key reasons: First, it has strong backing from Microsoft and is deeply integrated into Visual Studio, VS Code, and other Microsoft products. The tooling support is excellent. Second, Angular — one of the most popular web frameworks — is written in TypeScript.

Why I stop using TypeScript? ›

The TypeScript syntax is horrible and they have complicated things a lot to end up with a language that looks verbose like Rust but without any of its advantages, I think that projects like ReScript do everything better than TypeScript, but they have the problem of not being compatible with the main frameworks ; ...

What to avoid in TypeScript? ›

10 Common Mistakes in Typescript Development
  • Overuse of type “any”
  • Misusing “as” Casts.
  • Ignoring Type-check Errors and Warning.
  • Not Using Strict Mode.
  • Implicit “any” in Function Return Types.
  • Not using “const” and “read-only” correctly.
  • Inconsistent Coding Conventions.
  • Overcomplicating Types.

Is TypeScript frontend or backend? ›

That being said, since JavaScript can be used for both the front end and backend, and since TypeScript compiles into JavaScript, then it can be said and understood that TypeScript supports both the front end and backend.

Is TypeScript still relevant in 2024? ›

In 2024, both JavaScript and TypeScript have their place in the web development ecosystem. JavaScript's flexibility and ease of use make it perfect for quick projects and scripting, while TypeScript's robustness shines in larger, more complex applications.

What is the goal of TypeScript? ›

The goal of TypeScript is to be a static typechecker for JavaScript programs - in other words, a tool that runs before your code runs (static) and ensures that the types of the program are correct (typechecked).

Is TypeScript still in demand? ›

DevJobsScanner identified that JavaScript/TypeScript, Python, Java, C++ and Go are the most in-demand. Therefore, these 12 languages are likely to be the ones to learn in 2023.

Why do we use symbols in TypeScript? ›

Symbols are useful for creating unique keys in objects, avoiding naming collisions, and providing a way to define private-like properties and methods in classes. They also help in meta-programming scenarios, such as defining well-known symbols to customize object behavior.

Why do we use this keyword in Angular? ›

this refers to the component itself for which the template was rendered. On the template you can access only members of the component. This means that this is implicitly added to each property which you use in the template. This two accesses are the same - the 2nd one implicitly use this in front of it.

Why do we use three dots in TypeScript? ›

The three dots (...) in JavaScript is known as the spread operator, and it's used to make shallow copies of JavaScript objects. The spread syntax, or … in JavaScript, is a new addition to the set of operators in JavaScript ES6. It takes in an iterable, like an array, and expands it into individual elements.

What does this do in JS? ›

The this keyword refers to the context where a piece of code, such as a function's body, is supposed to run. Most typically, it is used in object methods, where this refers to the object that the method is attached to, thus allowing the same method to be reused on different objects.

Top Articles
Is Taking a Home Office Deduction Smart?
Is the Internet Considered A Utility Bill? (Here's the Answer)
Mickey Moniak Walk Up Song
Jail Inquiry | Polk County Sheriff's Office
Kmart near me - Perth, WA
Custom Screensaver On The Non-touch Kindle 4
13 Easy Ways to Get Level 99 in Every Skill on RuneScape (F2P)
Craigslist Portales
Davante Adams Wikipedia
Hertz Car Rental Partnership | Uber
Select The Best Reagents For The Reaction Below.
Craigslist Phoenix Cars By Owner Only
Moe Gangat Age
Mary Kay Lipstick Conversion Chart PDF Form - FormsPal
Kris Carolla Obituary
Available Training - Acadis® Portal
Grasons Estate Sales Tucson
Uky Linkblue Login
Webcentral Cuny
Union Ironworkers Job Hotline
Wausau Marketplace
Account Suspended
Selfservice Bright Lending
Manuela Qm Only
Idle Skilling Ascension
Random Bibleizer
Villano Antillano Desnuda
Tactical Masters Price Guide
Shia Prayer Times Houston
Evil Dead Rise Showtimes Near Regal Sawgrass & Imax
Kleinerer: in Sinntal | markt.de
Math Minor Umn
Abga Gestation Calculator
Mega Millions Lottery - Winning Numbers & Results
Appleton Post Crescent Today's Obituaries
Helloid Worthington Login
Domina Scarlett Ct
Restored Republic December 9 2022
This 85-year-old mom co-signed her daughter's student loan years ago. Now she fears the lender may take her house
Citibank Branch Locations In Orlando Florida
Directions To The Closest Auto Parts Store
Ucsc Sip 2023 College Confidential
2017 Ford F550 Rear Axle Nut Torque Spec
Honkai Star Rail Aha Stuffed Toy
Avatar: The Way Of Water Showtimes Near Jasper 8 Theatres
Wgu Admissions Login
RubberDucks Front Office
Wolf Of Wallstreet 123 Movies
Sinai Sdn 2023
Argus Leader Obits Today
Grandma's Portuguese Sweet Bread Recipe Made from Scratch
Karen Kripas Obituary
Latest Posts
Article information

Author: Tyson Zemlak

Last Updated:

Views: 5654

Rating: 4.2 / 5 (43 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Tyson Zemlak

Birthday: 1992-03-17

Address: Apt. 662 96191 Quigley Dam, Kubview, MA 42013

Phone: +441678032891

Job: Community-Services Orchestrator

Hobby: Coffee roasting, Calligraphy, Metalworking, Fashion, Vehicle restoration, Shopping, Photography

Introduction: My name is Tyson Zemlak, I am a excited, light, sparkling, super, open, fair, magnificent person who loves writing and wants to share my knowledge and understanding with you.