Fundamentos de TypeScript

1

¿Qué es TypeScript y por qué usarlo?

2

Instalación de Node.js y TypeScript CLI, configuración de tsconfig.json

3

Tipos primitivos: string, number, boolean, null, undefined de Typescript

4

Tipos especiales: any, unknown, never, void de TypeScript

5

Arrays, Tuplas, Enums en TypeScript

Funciones e Interfaces

6

Declaración de funciones, tipado de parámetros y valores de retorno

7

Parámetros opcionales, valores por defecto y sobrecarga de funciones

8

Creación y uso de interfaces de TypeScript

9

Propiedades opcionales, readonly, extensión de interfaces en TypeScript

Clases y Programación Orientada a Objetos

10

Creación de clases y constructores En TypeScript

11

Modificadores de acceso (public, private, protected) en Typescript

12

Uso de extends, sobreescritura de métodos en TypeScript

13

Introducción a Genéricos en Typescript

14

Restricciones con extends, genéricos en interfaces

Módulos y Proyectos

15

Importación y exportación de módulos en TypeScript

16

Agregando mi archivo de Typescript a un sitio web

17

Configuración de un proyecto Web con TypeScript

18

Selección de elementos, eventos, tipado en querySelector en TypeScript

19

Crear un proyecto de React.js con Typescript

20

Crea un proyecto con Angular y Typescript

21

Crea una API con Typescript y Express.js

Conceptos Avanzados

22

Introducción a types en TypeScript

23

Implementación de Decoradores de TypeScript

24

Async/await en Typescript

25

Pruebas unitarias con Jest y TypeScript

26

Principios SOLID, código limpio, patrones de diseño en Typescript

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
16 Hrs
44 Min
45 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

Crea una API con Typescript y Express.js

21/26
Resources

Creating APIs with TypeScript and Express represents a powerful combination for developers looking for robustness and security in their applications. TypeScript's static typing system perfectly complements the capabilities of Express, making it possible to build more reliable and maintainable web services. This synergy not only improves the development experience, but also strengthens the quality of the final product.

Why build APIs with TypeScript?

TypeScript offers significant advantages when it comes to developing APIs, especially when working with Express as a framework. Static typing allows us to clearly define the structure of the data flowing through our application, resulting in:

  • Greater security in data handling.
  • Better development experience with auto-completion and early error detection.
  • More maintainable and self-documented code.
  • Easier to work in large teams.

When we type the data we get from any data source, we can handle it with greater confidence and accuracy throughout our web application, reducing runtime errors.

How to set up an API project with TypeScript and Express?

To start developing an API with TypeScript and Express, we need to properly configure our development environment. This process involves several important steps:

Initializing the project.

First, we create a proper folder structure and initialize our project with npm:

mkdir APIcd APInpm init -y

This command creates a basic package.json file that will allow us to manage the dependencies of our project.

Installing dependencies

Next, we need to install Express and the dependencies related to TypeScript:

npm install express cors dotenvnpm installtypescript ts-node @types/node @types/express @types/cors --save-dev.

These dependencies are fundamental:

  • Express: The framework to create our API.
  • cors: To handle cross-origin requests.
  • dotenv: To manage environment variables.
  • TypeScript and ts-node: To compile and execute TypeScript code.
  • @types/...: Type definitions for the libraries we use.

TypeScript configuration

We create a tsconfig.json file to configure TypeScript:

{ " compilerOptions": { " target": "es6", " module": "commonjs", " outDir": "./dist", " strict": true, " esModuleInterop": true }}

This configuration sets:

  • The output directory for the compiled files(dist).
  • The type of module we will use(commonjs).
  • The interoperability between ES and CommonJS modules.

Project structure

It is advisable to organize our code in a clear structure. For example:

API/├─── src/│ └── server.ts├─── package.json└── tsconfig.json

How to implement a basic server with Express and TypeScript?

Once the environment is configured, we can create our Express server with TypeScript. The basic implementation is similar to pure Node.js, but with the advantage of static typing.

Creating the server

In the src/server.ts file, we implement our server:

import express from 'express';import cors from 'cors';import dotenv from 'dotenv';
// Environment variable configurationdotenv.config();
// Express application initializationconst app = express();const PORT =process.env.PORT || 3000;
// Middlewareapp.use(cors());app.use(express.json());
// Routesapp.get('/hello', (req, res) => { res.send('Hello from API with TypeScript');});
// Initializing the serverapp.listen(PORT, () => { console.log(`Serverrunning at http://localhost:${PORT}`);});

Configuring scripts in package.json

For ease of development and compilation, we configure scripts in our package.json:

{ " scripts": { " start": "node dist/server.js", " dev": "ts-node src/server.ts", " build": "tsc" }}

These scripts allow us to:

  • dev: Run the application in development mode with ts-node.
  • build: Compile the TypeScript code to JavaScript.
  • start: Run the compiled version of the application.

Running the server

To start the server in development mode, we execute:

npm run dev

If everything is configured correctly, we will see the message "Server running at http://localhost:3000" and we can access the /hello path in our browser to see the message "Hello from the API with TypeScript".

The syntax for creating routes in Express with TypeScript is virtually identical to that of pure JavaScript, but with the added advantage of typing. We can easily implement the standard HTTP methods:

// GET - Get dataapp.get('/resources', (req, res) => { // Logic to get resources});
// POST - Create dataapp.post('/resources', (req, res) => { // Logic to create a resource});
// PUT - Update dataapp.put('/resources/:id', (req, res) => { // Logic to update a resource});
// DELETE - Delete dataapp.delete('/resources/:id', (req, res) => { // Logic to delete a resource});

The true power of TypeScript manifests itself when we start to type our data, request parameters and responses, allowing us to create more secure and maintainable APIs.

The combination of TypeScript and Express offers a perfect balance between flexibility and security for modern API development. Have you experimented with this combination in your projects? Share your experiences and questions in the comments.

Contributions 1

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

En TypeScript, tanto los `types` como las `interfaces` se utilizan para definir la forma de los objetos, pero tienen diferencias clave: 1. **Extensibilidad**: Las `interfaces` pueden ser extendidas mediante herencia, lo que permite crear nuevas interfaces basadas en otras. Los `types`, en cambio, no pueden ser extendidos de manera directa, aunque se pueden combinar usando intersecciones (por ejemplo, `type A = B & C`). 2. **Uniones**: Los `types` pueden ser usados para crear uniones (por ejemplo, `type A = string | number`), mientras que las `interfaces` no pueden. 3. **Definiciones múltiples**: Puedes declarar la misma `interface` múltiples veces, y TypeScript las combinará. Los `types` no permiten esto. Ambos se utilizan para agregar tipado fuerte, pero la elección depende del caso de uso específico y preferencias personales.