Type aliases – TypeScript Patterns for Angular
The last way to type a variable that we will see in this chapter is the simplest one, which is to create type aliases. Like interfaces, type aliases only exist in TypeScript, and we can use them as in the following example:
type Machine = {
id: number;
description: string;
energyOutput: number;
};
export function basic_type() {
let car: Machine = {
id: 123,
description: “Car”,
energyOutput: 1000,
};
console.log(ID:${car.id} Description:${car.description} Energy Output:${car.energyOutput}
);
}
In this code, we create the Machine type, describing the object we want to represent, and in the basic_type function, we instantiate a variable with that type.
Note that we use the attributes of this variable just like the previous examples. This demonstrates how much TypeScript maintains the flexibility of JavaScript while giving more possibilities to the developer.
A well-used feature of type aliases is the creation of a type from other types. One of the most common is the union of types, as we can see in the following code:
type ID = string | number;
type Machine = {
id: ID;
description: string;
energyOutput: number;
};
Here, we are creating a type called id, which can be string or number. For this, we use the | symbol, which is the same as used in JavaScript to indicate the conditional OR.
This feature was important for the use of more advanced techniques, such as the guard type, which we will see in this chapter.
When to use classes, interfaces, or types
With all these ways of creating typed objects, you must be wondering in which situations we should use each one. Based on the characteristics of each form, we can categorize the use of each one:
- Type alias: The simplest form of creation, recommended for typing input parameters and function returns.
- Interfaces: Recommended for representing JSON data objects, where we won’t have methods, just the data representation. An example is the return of an API that we will use in our Angular project. The interface can also be used to define class contracts using the implements keyword.
- Classes: The basis of object orientation, also present in JavaScript. We should use it whenever we need an object with methods and attributes. In Angular, all components and services are ultimately objects created from classes.
Remember that in TypeScript, it is possible to create an alias type that behaves as an interface, as well as indicate an interface as a parameter and return of a function, but the recommendations here advise you to use the best for each type of situation and also explain how they are normally used in Angular apps.
Now that we have a good understanding of the different ways of creating more complex variables as objects, let’s get to know how to create functions and methods with TypeScript.