GSD

What is TypeScript? The JavaScript Superset Explained

Posted by Maab Saleem on January 4, 2024

TypeScript (TS) is a superset of JavaScript (JS), developed and maintained by Microsoft as an open-source programming language. TypeScript can seamlessly integrate into existing JavaScript code, adding structure and catching type safety errors before they crash your app.

In this brief piece, we will delve into the fundamentals of TypeScript and explore why it’s become the go-to choice for modern web development.

Understanding the origins of TypeScript

For all its flexibility and dynamism, JavaScript lacks a crucial feature for building and maintaining large-scale applications: static typing. Since JavaScript is dynamically typed, variables can hold any data type, which may change on the fly without warning. This can lead to potential runtime errors that can be hard to detect during development.

Why it was created

TypeScript was conceived to solve these challenges and add predictability to JavaScript code. It introduces static typing, meaning you explicitly declare the types of variables, functions, and return types upfront. This approach guarantees type safety and reduces runtime surprises.

JavaScript vs. TypeScript – A comparison in code

For a better understanding, let’s look at an example. Consider a simple JavaScript function meant to concatenate two string variables:

function concatenate(a, b) {

    return a + b;

}

As you can see, this function doesn't enforce specific types for a and b. It allows any input, including numbers or other data types, to be passed.

However, if we pass a data type other than a string for a or b, the function might behave differently than intended. For example, if we pass two numbers to it, it will add them:

console.log(concatenate(1, 2)); // Output: 3

Now, let’s rewrite our function with static types in TypeScript:

function concatenate(a: string, b: string): string {

    return a + b;

}

Here, the function declaration explicitly specifies that both a and b must be of type string. It also indicates that the function will return a string value. This ensures that only string inputs are concatenated and any unexpected behavior is detected at compile time. For example:

// The following line will produce a TypeScript compilation error

// console.log(concatenate(1, 2));

TypeScript will log a compilation error at the above line, reminding the developer of their mistake before it causes any problems in production.

JavaScript and TypeScript – a symbiotic relationship

The beauty of TypeScript is that it doesn’t replace JavaScript; in fact, it compiles into it. Your existing JavaScript code can seamlessly integrate and coexist with TypeScript, allowing you to migrate at your own pace gradually. 

undefined

Why you should use TypeScript

There are many benefits of using TypeScript over JavaScript, including:

  • Explicitly declared types make the code self-documenting. This increases clarity and reduces cognitive load for both the original and subsequent developers. 

  • Any type-related errors are detected during the development process. This leads to fewer runtime bugs.

  • IDEs, like Visual Studio Code and WebStorm can use the type information to provide intelligent features like autocompletion, refactoring, and code navigation.

  • TypeScript makes large and complex codebases easier to maintain. For example, if you want to change the data type of a variable, you can use the IDE’s refactoring feature to update all references across the codebase automatically. This saves time and reduces the chances of human error.

  • TypeScript also introduces interfaces, a way to define clear contracts for objects. Interfaces establish rules that objects must adhere to, including the names and types of their properties and method signatures. For example, you can define an interface named Car that outlines the expected properties of a car object:

interface Car {

    make: string;

    model: string;

    year: number;

    startEngine: () => void;

    stopEngine: () => void;

}

This interface specifies that any object of type Car must have the makemodel, and year properties and implement the startEngine and stopEngine methods.

Learn how ButterCMS can revolutionize your content management.
Start my free trial

How does TypeScript work?

All TS code is compiled (or transpiled) into corresponding JS before execution. The TypeScript Compiler (tsc) performs this transformation. Let’s explore this process in more detail.

Conversion of TypeScript to JavaScript

Tsc checks the TypeScript code during compilation for syntax errors, type mismatches, and other potential issues. If the code passes these checks, tsc transpiles it into equivalent JavaScript code. 

The resulting JavaScript typically mirrors the structure and functionality of the original TypeScript but lacks TypeScript-specific syntax and types. It can run in any browser or JavaScript runtime environment.

On errors

However, if your code has any errors, the compilation is halted and error messages are displayed on the screen. For example: 

let age: number = "25"; 

For the above line, the compiler will throw an error like this:  Type string is not assignable to type number.

interface Person {

    name: string;

    age: number;

}

let person: Person = {

    name: 'Alice'

    // Error: we also need to specify `age` here

};

For this one, the error will say: Property age is missing in type { name: string; } but required in type Person.

Errors like these can slip through undetected when using JavaScript, particularly within larger codebases.

Getting started with TypeScript

To download TypeScript and integrate it into an existing or new project, run this command:

npm install typescript --save-dev

The yarn alternative is: 

yarn add typescript --dev

Once that’s done, you can:

  • Rename all existing .js files to .ts to start utilizing TypeScript features. Since TypeScript is a superset of JavaScript (i.e. all JavaScript code is valid TypeScript code), this is safe to do.

  • Gradually start adding type annotations to existing code for enhanced type safety.

Setting up the tsconfig.json file

Run the following command to create a tsconfig.json file:

npx tsc --init

The yarn alternative is:

yarn tsc --init

Once the tsconfig file has been created, you can open it in your favorite editor and tweak it as necessary. For example, you can:

  • Set the target parameter to the desired ECMAScript version (e.g., "target": "es2021").

  • Define outDir to specify the output directory for compiled JavaScript files (e.g., "outDir": "./").

  • Adjust the value of strict to enforce all strict type-checking options. (e.g., “strict”: true).

To dive deeper, explore the official TypeScript docs or experiment with the TypeScript playground on the official site.

Best practices for using TypeScript

Remember the following guidelines when writing TypeScript code:

  • Clearly define types for variables, parameters, and return values to maximize code clarity. Minimize using the any type as it bypasses TypeScript's type checking.

  • Use generics to write functions that work with any data type. This boosts code reusability and avoids unnecessary typecasting.

  • Use interfaces to define clear and reusable data structures.

  • Integrate static analysis tools like typescript-eslint into your development workflow. They can help enforce coding standards, identify potential issues, and improve code quality.

  • Stay updated with TypeScript versions to adopt new features and benefit from improved language capabilities. 

When should you reconsider using TypeScript?

Even though TypeScript offers undeniable advantages over JavaScript, there are some situations where you might want to reconsider using it. For example:

  • The overhead of TypeScript's type annotations and configuration might outweigh its benefits for quick scripts or throwaway prototypes. JavaScript may be a better option in such scenarios. 

  • If you're pressed for time and/or your team lacks TypeScript expertise, consider sticking with JavaScript. Introducing a new language may slow down development.

  • Adding TypeScript to a large, poorly documented JavaScript codebase can be challenging and resource-intensive. Before switching, weigh the benefits of improved maintainability against the migration effort and potential compatibility issues.

Wrapping up

TypeScript is a JavaScript superset that helps developers write inherently safer and more maintainable code. In this post, we covered everything you need to know to get started with TypeScript; we hope you found it useful.

Make sure you receive the freshest tutorials and Butter product updates.
Maab Saleem

Maab is an experienced software engineer who specializes in explaining technical topics to a wider audience.

ButterCMS is the #1 rated Headless CMS

G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award

Don’t miss a single post

Get our latest articles, stay updated!