Creating classes and types – TypeScript Patterns for Angular
Since version 2 of the framework, Angular is based on TypeScript for its development, both internally and for those who use it to build applications.
This was a controversial decision at the time, as this JavaScript superset, created by Microsoft, was new. Nowadays, most web frameworks, such as React, Vue.js, and Svelte, support TypeScript, and some web frameworks actively recommend TypeScript as the language to use.
In this chapter, we will study the best practices and patterns for using TypeScript with Angular and beyond; these techniques can be applied to Node.js backend development and even other web frameworks, such as React and Vue.js.
We’ll learn how to better declare our application’s methods and functions and how to leverage TypeScript’s type inference mechanism to make our classes less verbose.
In this chapter, we’re going to cover the following topics:
- Creating classes and types
- Creating methods and functions
- Decreasing verbosity: type inference
- Validating types: type guards
- Using a better alternative to the any type
By the end of the chapter, you will be able to better apply TypeScript resources in your projects, improving the quality of your code and the productivity of your team.
Technical requirements
To follow the instructions in this chapter, you’ll need the following:
- Visual Studio Code (VS Code) (https://code.visualstudio.com/Download)
- Node.js 18 or higher (https://nodejs.org/en/download/)
The code files for this chapter are available at https://github.com/PacktPublishing/Angular-Design-Patterns-and-Best-Practices/tree/main/ch3.
Creating classes and types
The basis of application development using Angular is object-oriented programming, so it is important for us to delve into how to create classes and instantiate objects. Using TypeScript instead of pure JavaScript, we have another powerful element in our toolbox of types.
By typifying variables and objects, the TypeScript transpiler is able to carry out checks and alerts, preventing errors that could occur at runtime during development if this process did not exist.
Bear in mind that after transpiling (a process that transforms TypeScript code into JavaScript), the code delivered to the client’s browser is pure JavaScript, including some optimizations; that is, code written in TypeScript is no less performant than code written directly in JavaScript.
To start with the fundamentals, let’s explore primitive and basic types.