Introduction

Developed by Microsoft back in 2012, TypeScript is a powerful programming language that extends JavaScript, allowing developers to write code with static type-checking and other modern features. This post will explore the fundamentals of TypeScript, discuss the benefits of using it, and provide code examples to illustrate these concepts.

Understanding the Basics of TypeScript

TypeScript is a typed superset of JavaScript. This means that it includes all of the capabilities of JavaScript, plus additional features that are not available in the language. TypeScript code is compiled into plain JavaScript code which can be used in any JavaScript runtime environment. This makes it possible to use TypeScript on both the client-side and server-side of an application.

TypeScript enables developers to use static type-checking, which is a powerful feature that can be used to detect errors in code before it is deployed. This makes it easier to detect and fix errors early on, saving time and effort. Additionally, TypeScript uses an interface system that allows developers to define data types for variables. This makes it easier to read and understand code, and can help reduce the likelihood of errors.

Benefits of Using TypeScript

One of the main benefits of using TypeScript is that it provides a smoother development experience. This is because TypeScript code is easier to read, which makes it easier to debug and make changes. Additionally, TypeScript enables developers to use modern features like classes and modules, which make it easier to structure and organize code.

TypeScript also makes it easier to maintain code over time. The static type-checking system ensures that code remains consistent and that changes don’t break existing functionality. This makes it easier to make changes and add new features without having to worry about breaking existing code.

Types

Below is a list of the most common types you’ll come across.

string: Represents string values such as “Hello World”.

number: Represents numerical values like 1 or 3.5.

boolean: Represents true or false.

number[] or Array<number>: Represents an array of numbers.

string[] or Array<string>: Represents an array of strings.

[type, type]: Represents a tuple where two types can be declared. E.g. [number, string].

enum: Represents an enum.

any: Represents any value (TypeScript will not throw typechecking errors).

See the full list here!

Examples

To illustrate the benefits of TypeScript, let’s take a look at some examples of code written in the language.

Type Safety

Let’s start by declaring a variable and assigning a value to it.

let myNumber = 10;

Now, let’s say we reassign myNumber but this time, to a string value.

let myNumber = 10;
myNumber = "Hello World";

Excuse me, what?

There isn’t anything in JavaScript to check the type of variable declared, meaning that it can be reassigned later to a different type.

That’s exactly what TypeScript fixes! Let’s contrast the above example to one using TypeScript.

let myNumber: number = 10;
myNumber = "Hello World" // ERROR: Type 'string' is not assignable to type 'number'.ts(2322)

If we declare myNumber is of type number, then TypeScript won’t let us reassign it to a string.

Classes in TypeScript

Now, here is an example of a class written in TypeScript:

class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
      this.name = name;
      this.age = age;
  }
}

If you’ve used other strongly typed languages like C# or Java, the above code may look familiar. We create a class Person, which contains two properties: name and age. The static type-checking system ensures that these properties are always strings and numbers, respectively. Additionally, the interface system allows us to define these types and ensure that they remain consistent.

Here is an example of a function written in TypeScript:

function add(a: number, b: number): number {
  return a + b;
}

This function takes two numbers as parameters and returns the sum of them. The static type-checking system ensures that these parameters are always numbers, and that the return value is also a number. This makes it easier to read and understand code, and helps to prevent errors.

Interfaces in TypeScript

Interfaces in TypeScript are much like interfaces in other languages. They allow us to define and enforce contracts within our code. Let’s look at an example.

interface User {
	id: number;
	firstName: string;
	lastName: string;
	age: number;
}

function printName(user: User) {
	console.log(`${user.firstName} ${user.lastName}`);
}

In the above example, we declare an interface User, and assign its properties accordingly. Then, we declare a function to print a User object’s firstName and lastName fields. Just like in our previous example, if we try to assign a value that is not of type string to our firstName or lastName fields, TypeScript will throw an error. Similarly, the id and age fields must be numerical values.

Where to Begin

TypeScript is completely free and super easy to set up.

If you have Node installed, simply run:

npm i typescript --save-dev

Once installed, we can initialize it using the following command:

npx tsc --init

You’ll see a tsconfig.json file has been generated. This file will allow you to configure TypeScript and its many options.

That’s all the setup that is required to start using TypeScript. The next step is to create a TypeScript file (.ts file extension), and once you’re ready, run:

npx tsc

The above command will compile your TypeScript code into JavaScript code which can then be deployed.

That’s it. You’re ready to start your journey as a TypeScript developer!

Conclusion

TypeScript is a powerful programming language that extends JavaScript, providing developers with a smoother development experience and improved code quality. By enabling static type-checking, TypeScript makes it easier to detect and fix errors early on, and its interface system makes it easier to read and understand code. With these benefits, TypeScript is an excellent choice for any application that requires a powerful, modern language. This has been a brief introduction to TypeScript, but if you’re interested, here is the full documentation for TypeScript.