Skip to content

Introduction to TypeScript

Chapter Objectives

  • ✔️
    Discover TypeScript
    Learn how to create your first TypeScript model.

What is TypeScript?

TypeScript is a superset of JavaScript that compiles to plain JavaScript. TypeScript is purely object-oriented with classes, interfaces and is statically typed like C# or Java.

Why use TypeScript?

Using TypeScript offers several advantages:

  • Type Safety: TypeScript provides static typing, which helps you catch errors at compile time rather than runtime. This can help you detect bugs earlier and improve your code quality.
  • Tools: TypeScript provides a rich set of tools for building and maintaining large-scale applications. This includes features such as code completion and easier refactoring.
  • Readability: TypeScript provides a way to add type annotations to your code, which can make it easier to understand and maintain.

Take a car object, in Javascript, we accept the following format:

const car = {
make: "Toyota",
model: "Corolla",
year: 2020,
};

To log the car’s model, you would do:

console.log(car.model);

But not only do you have to remember the car object’s structure, you also need to remember the type of each property. This makes code maintenance and understanding more complicated.

In TypeScript, you can define a Car interface like this:

export interface Car {
make: string;
model: string;
year: number;
}

A type is a set of elements that allow us to categorize information. In this example, not only do we bind different characteristics of a car like its model or manufacturer, but we also define the actual type of each property. We will therefore handle strings for the model and manufacturer but a number for the year.

And then you can use it like this:

const car: Car = {
make: "Toyota",
model: "Corolla",
year: 2020,
};

What are the benefits of using TypeScript?

Auto-completion

When you define a type for a variable, you get auto-completion for that type’s properties.

Type checking

TypeScript will check if you’re using the correct type for a variable.

IDE Support

Your IDE will warn you if you use the wrong type for a variable.

Compilation Errors

TypeScript will detect errors at compile time.

✔️ What you’ve learned

In this chapter, you learned how to create your first TypeScript model. You learned how to define a TypeScript interface and use it to create a new object.