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
14 Hrs
55 Min
39 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

Async/await en Typescript

24/26
Resources

Asynchronous communication in TypeScript is a powerful tool that allows operations to be executed outside of the main thread of execution, significantly improving the user experience by keeping the interface responsive while processing data in the background. This functionality is essential for developers looking to create modern and efficient web applications.

How to implement asynchronous communication in TypeScript?

Asynchronous communication in TypeScript is very similar to that used in Node.js, making it easy to implement if you already have prior experience with JavaScript. To demonstrate how it works, we will create a small project that uses the fetch method to fetch data from an API and display it on a web page.

First, we need to create the basic structure of our project:

  1. Create a folder called "fetch".
  2. Inside this folder, create a basic HTML file.
  3. Create a TypeScript file to handle the logic

Preparing the HTML

Our HTML file will be simple, with just a button to request information and a paragraph to display the results:

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>FetchExample</title></head></head><body> <button class="btnInfo">RequestInfo</button> <p class="info">Herewill appear the information....</p> <script src="main.js"></script></body></html></html>

Implementing the logic in TypeScript

Now, we will create a main.ts file that will contain the logic to fetch the data and display it on the page:

const fetchData = async (url: string) => { const response = await fetch(url); const data = await response.json(); return data;};
let button = document.querySelector('.btnInfo') as HTMLButtonElement;let paragraph = document.querySelector('.info') as HTMLParagraphElement;
button.addEventListener('click', async () => { const data = await fetchData(' https://microsoftedge.github.io/Demos/json-dummy-data/64KB.json'); paragraph.textContent = JSON.stringify(data);});

In this code:

  1. We create an asynchronous function fetchData that receives a URL and returns the data in JSON format.
  2. We select the HTML elements we will interact with
  3. We add a click event to the button that, when triggered, will fetch the data and display it in the paragraph

The use of the await operator is critical here, as it allows the application to continue running while waiting for the API response, without blocking the main thread.

Configuring TypeScript for interoperability with HTML

In order for our TypeScript code to work correctly with HTML, we need to create a configuration file tsconfig.json:

{ " compilerOptions": { " target": "ES2015", " module": "ES2015", " lib": ["DOM", "ES2015"], " esModuleInterop": true }}

This configuration is crucial because:

  1. It includes the DOM library to be able to interact with HTML elements.
  2. Sets the proper compilation target
  3. Configures module interoperability

How to compile TypeScript code correctly?

A common mistake when working with asynchronous code in TypeScript is to encounter problems during compilation. If you try to compile the file with a simple tsc main.ts, you may receive errors related to asynchronous promises or functions.

To avoid these problems, you should compile using the configuration file:

tsc -p tsconfig.json.

This command tells the compiler to use the options defined in the tsconfig.json file, which will allow the asynchronous code to compile correctly.

How to extend this practice for real applications?

The example shown is basic, but you can expand it to create more complex applications:

  • Process JSON data to extract specific information.
  • Dynamically create HTML elements to display data in a structured way
  • Implement error handling for fetch requests
  • Add loading indicators while fetching data

For example, you could modify the code to display the data in a table or cards, instead of just dumping all the JSON into a paragraph:

button.addEventListener('click', async () => { try { const data = await fetchData(' https://microsoftedge.github.io/Demos/json-dummy-data/64KB.json' );        
 // Process the data and display it in a structured way let formattedOutput = ''; for (const [key, value] of Object.entries(data)) { formattedOutput += `<strong>${key}:</strong> ${value}<br>`; }        
 paragraph.innerHTML = formattedOutput; } catch (error) { paragraph.textContent = `Errorgetting data: ${error.message}`; } } });

Asynchronous communication is an essential skill for any TypeScript developer, as it allows you to create faster and more responsive applications. Practicing with these concepts will help you master one of the most powerful features of modern web development. Have you implemented asynchronous communication in your projects? Share your experiences in the comments.

Contributions 1

Questions 0

Sort by:

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

Un dato curioso sobre `async/await` en TypeScript es que, aunque parece que devuelve valores normales, **siempre retorna una** `Promise` **internamente**. B谩sicamente, `async/await` es solo una forma m谩s elegante de trabajar con `Promises`, pero bajo el cap贸 sigue funcionando igual.