TypeScript has a number of key features that fun­da­ment­ally improve web ap­plic­a­tion de­vel­op­ment. This TypeScript tutorial gives you an in­tro­duc­tion to the pro­gram­ming language and explains some of its most important features and uses as well as its ad­vant­ages and dis­ad­vant­ages.

What is TypeScript?

TypeScript was developed by Microsoft and builds upon the pro­gram­ming language JavaS­cript, which is widely used in web de­vel­op­ment. One feature of TypeScript that stands out is static typing. Unlike JavaS­cript, which has dynamic typing, TypeScript allows you to declare data types for variables, functions and para­met­ers. This allows for early detection of coding errors, making it possible to identify errors even before the code has been executed. Static typing not only sig­ni­fic­antly improves code quality, it also improves code read­ab­il­ity.

The TypeScript syntax is almost identical to JavaS­cript, which makes in­teg­rat­ing it into existing JavaS­cript projects a lot easier. In fact, TypeScript is a superset of JavaS­cript, which means that any JavaS­cript code that is correct is also valid TypeScript code. This allows you to gradually migrate to TypeScript and benefit from the ad­vant­ages of static typing and other features without having to com­pletely rewrite your existing codebase.

Here is a simple JavaS­cript example:

function greet(name) {
    return "Hello, " + name;
}
console.log(greet(123)); // Output: "Hello, 123"
javas­cript

In the code above, the greet function is not re­stric­ted to a specific data type for the name parameter. This means that the function will still work, even if we pass a number as an argument.

In TypeScript, the code may look like this:

function greet(name: string): string {
    return "Hello, " + name;
}
console.log(greet(123)); // Error in TypeScript
typescript

Here we have declared the parameter name as a string. If we try to use the function with a number, TypeScript will display an error because the passed data type does not match the expected data type.

This example shows how TypeScript helps detect errors early on, enhancing the quality of the code by pre­vent­ing the incorrect use of data types. It is important to note that TypeScript is even­tu­ally compiled to JavaS­cript, making it possible to run it in any JavaS­cript en­vir­on­ment. This, however, means that you only get the benefits of type safety during the de­vel­op­ment phase.

What is TypeScript used for?

TypeScript is an essential for various areas of software de­vel­op­ment, es­pe­cially in situ­ations where type safety and code quality are of crucial im­port­ance.

A prominent use case for TypeScript is web de­vel­op­ment. Here, TypeScript ensures that JavaS­cript code is written in a way that makes it more secure and easier to maintain. This is be­ne­fi­cial in extensive frontend projects with complex codebases. However, TypeScript can also be im­ple­men­ted on the server side (backend) in Node.js ap­plic­a­tions to provide an ad­di­tion­al layer of security. In server­less ar­chi­tec­tures such as AWS Lambda and Azure Functions, TypeScript helps to minimise errors and ensure reliable execution.

Cross-platform de­vel­op­ment is yet another area where TypeScript showcases its strengths. It can sig­ni­fic­antly optimise cross-platform ap­plic­a­tions and mobile app de­vel­op­ment. Frame­works such as Nat­iveScript and React Native offer support for TypeScript when it comes to pro­gram­ming mobile apps for different platforms. In game de­vel­op­ment, TypeScript is utilised in projects that use WebGL or game engines such as Phaser or Babylon.js. TypeScript’s type safety helps to improve game quality and main­tain­ab­il­ity.

TypeScript is also used for data visu­al­isa­tion and analysis projects. Libraries such as D3.js provide support for TypeScript and enable the creation of soph­ist­ic­ated dash­boards and visu­al­isa­tions.

Cheap domain names – buy yours now
  • Free website pro­tec­tion with SSL Wildcard included
  • Free private re­gis­tra­tion for greater privacy
  • Free Domain Connect for easy DNS setup

How to install TypeScript

In­stalling TypeScript is simple and only takes a few steps. If you have Node.js on your computer, you can install TypeScript with npm (Node Package Manager).

Step 1: Download Node.js

Check whether you have Node.js installed on your computer. If you have not yet set up Node.js, you can download and install it from the official website.

Step 2: Install TypeScript in the terminal

Open your command prompt (e.g. Command Prompt in Windows or the terminal on macOS or Linux) and enter the following command to install TypeScript globally:

npm install -g typescript
bash

The -g (global) flag installs TypeScript on your entire system so that you can use it from anywhere.

Step 3: Check the installed version

You can test whether the in­stall­a­tion was suc­cess­ful by executing the following command:

tsc -v
bash

This command shows which version of TypeScript is installed. If a version number is shown, it means the in­stall­a­tion was suc­cess­ful.

After in­stall­a­tion, you can generate JavaS­cript files by creating TypeScript files (with the extension .ts) and compiling them with the TypeScript compiler tsc.

Step 4: Create a TypeScript file

Create a TypeScript file, e.g., app.ts, and insert your TypeScript code.

type Person = { name: string, age: number };
const alice: Person = { name: "Alice", age: 30 };
console.log(`Hello, I am ${alice.name} and I am ${alice.age} years old.`);
typescript

Step 5: Compile the file

Compile the TypeScript file by entering the following command:

tsc app.ts
bash

This will compile app.ts into a JavaS­cript file with the name app.js. You can then execute the JavaS­cript file.

What features does TypeScript have?

Web de­vel­op­ment has made sig­ni­fic­ant progress in recent years, and TypeScript has emerged as an extremely efficient al­tern­at­ive to JavaS­cript. Below, we’ve sum­mar­ised the most important features of this language.

Static typing

Static typing is an essential feature of TypeScript that lets you specify data types for variables, para­met­ers, functions and other elements within your code. Unlike dynamic typing in JavaS­cript, where data types are de­term­ined during execution, in TypeScript data types are assigned during de­vel­op­ment before the code is executed. This method helps to identify errors and logical issues early on.

function add(a: number, b: number): number {
    return a + b;
}
const result = add(5, 3); // valid
const result = add(5, "3"); // Type Error
typescript

In this example, we used static typing for the add function. The two para­met­ers a and b are declared as numbers (number) and the function returns a value of type number. Any attempt to use this function with a different data type will cause TypeScript to identify it as an error.

Optional typing

With optional typing, you have the ability to specify data types for certain variables and para­met­ers, while leaving others without a defined data type.

function sayHello(name: string, age: any): string {
    if (age) {
        return `Hello, ${name}, you are ${age} years old.`;
    } else {
        return `Hello, ${name}.`;
    }
}
typescript

The sayHello function is defined with the para­met­ers name and age. The des­ig­na­tion any indicates that the age parameter can be any data type.

ES6+ features

TypeScript supports modern JavaS­cript features, including ES6 and newer features such as arrow functions and template strings.

const multiply = (a: number, b: number): number => a * b;
const greeting = (name: string) => `Hello, ${name}!`;
typescript

The arrow functions lead to a shorter and more concise syntax.

Code or­gan­isa­tion

TypeScript offers better code or­gan­isa­tion and ensures that code is divided into reusable parts. This is made possible due to modules and namespaces.

// Math.ts
export function add(a: number, b: number): number {
    return a + b;
}
// Main.ts
import { add } from './Math';
const result = add(5, 3);
typescript

Here, we demon­strate how to structure code with modules and utilise import and export for or­gan­isa­tion. The add function is defined within a distinct module named Math.ts and then imported and in­teg­rated into a different module, Main.ts.

Object-oriented pro­gram­ming (OOP)

TypeScript fa­cil­it­ates object-oriented pro­gram­ming through TypeScript classes, in­ter­faces and in­her­it­ance:

class Person {
    constructor(public name: string, public age: number) {}
    greet() {
        console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
    }
}
const person = new Person("Alice", 30);
person.greet();
typescript

This example shows the use of classes and object-oriented pro­gram­ming (OOP) in TypeScript. The class Person has the prop­er­ties name, age and a method greet, which is used to introduce the person and provide in­form­a­tion about them.

Extended type system

The TypeScript type system is flexible and extensive. You can create user-defined types and in­ter­faces and even extend existing types.

interface Animal {
    name: string;
}
 
interface Dog extends Animal {
    breed: string;
}
const myDog: Dog = { name: "Buddy", breed: "Labrador" };
typescript

The interface Animal defines a property name, while the interface Dog inherits from Animal and adds an ad­di­tion­al property breed. The object myDog has the char­ac­ter­ist­ics of both in­ter­faces.

Com­pat­ib­il­ity with JavaS­cript

TypeScript is com­pat­ible with JavaS­cript, allowing it to run in any JavaS­cript en­vir­on­ment. This com­pat­ib­il­ity makes it easier to pro­gress­ively in­cor­por­ate TypeScript into current JavaS­cript projects.

// JavaScript-Code
function greet(name) {
    return "Hello, " + name;
}
// TypeScript-Code
function greet(name: string): string {
    return "Hello, " + name;
}
typescript

The JavaS­cript code above (without typi­fic­a­tion) can be used in a TypeScript code (with typi­fic­a­tion) without any problems.

What are the ad­vant­ages and dis­ad­vant­ages of TypeScript?

While TypeScript offers a number of ad­vant­ages, it also comes with some dis­ad­vant­ages. Here is an overview:

Ad­vant­ages

TypeScript has an extensive ecosystem of type defin­i­tions for many JavaS­cript libraries and frame­works. This makes in­teg­rat­ing third-party code into TypeScript projects seamless and straight­for­ward. This is helpful in today’s world of web-based ap­plic­a­tions that often rely on multiple libraries and frame­works.

In addition to static typing, TypeScript offers a wealth of de­vel­op­ment features, including in­ter­faces, classes, modules and support for current ECMAScript standards. These features improve the struc­tur­ing of the code, fa­cil­it­ate the main­tain­ab­il­ity and scalab­il­ity of projects, and promote pro­ductiv­ity in de­vel­op­ment. Many in­teg­rated de­vel­op­ment en­vir­on­ments (IDEs) such as Visual Studio Code provide excellent support for TypeScript.

Dis­ad­vant­ages

TypeScript takes time to get used to, es­pe­cially for de­velopers that have only worked with JavaS­cript prior to using it. TypeScript code must be compiled in JavaS­cript before it can be executed in browsers or Node.js en­vir­on­ments. This creates an ad­di­tion­al step in the de­vel­op­ment process.

In smaller projects, TypeScript can be perceived as overly complex, as the benefits of type safety may not be as obvious. TypeScript projects may require more resources due to ad­di­tion­al type in­form­a­tion and com­pil­a­tion steps.

What are some al­tern­at­ives to TypeScript?

There are various web pro­gram­ming languages that may be a good al­tern­at­ive to TypeScript depending on a project’s specific re­quire­ments and the pref­er­ence of the developer(s).

  • Flow: Flow is a static type checker for JavaS­cript that was developed by Facebook. It allows you to add types to JavaS­cript code without having to make a complete switch to TypeScript. Flow is a good choice if you want to gradually integrate typing into your JavaS­cript projects.
  • Dart: this is a pro­gram­ming language developed by Google that can be used to create web ap­plic­a­tions and mobile apps. It offers type safety and good per­form­ance. Dart is often used in com­bin­a­tion with the Flutter framework for mobile app de­vel­op­ment.
  • Pure­Script: Pure­Script is a strongly typed func­tion­al pro­gram­ming language that includes strong type safety and a purely func­tion­al pro­gram­ming style. It enables JavaS­cript libraries to be imported.
  • Elm: Elm is a func­tion­al, strongly typed language designed for the de­vel­op­ment of weyb ap­plic­a­tions. Elm promotes the principle of Elm Ar­chi­tec­ture and has a high level of type safety.
  • ReasonML (BuckleScript): this language was developed by Facebook and is based on OCaml. BuckleScript is a compiler that compiles ReasonML into JavaS­cript. It also enables type safety and is easy to integrate with React for frontend de­vel­op­ment.
Tip

We delve deeper into other topics such as TypeScript functions and TypeScript arrays in other articles in our Digital Guide.

464928e530bccfab16fba70639311fb9

f9da1c6cf9adef7aa5114f0cfa7742bf

Go to Main Menu