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
37 Min
43 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

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

18/26
Resources

The integration of TypeScript with HTML opens up a world of possibilities for manipulating the DOM in a safe and efficient way. Through this powerful combination, we can access HTML elements, modify their content, and respond to user events with the type safety that TypeScript provides. Let's see how we can leverage these capabilities to create more robust and maintainable web applications.

How to interact with the DOM from TypeScript?

TypeScript allows us to access and manipulate DOM elements with the same ease as JavaScript, but with the added benefit of type checking. This means that we can detect potential errors during development, before they reach production.

To start interacting with the DOM from TypeScript, we need:

  1. An HTML file with the elements we want to manipulate.
  2. A TypeScript file that will access these elements.
  3. Compiling the TypeScript file to JavaScript so that the browser can interpret it.

Accessing HTML elements using querySelector

There are several ways to select DOM elements in TypeScript, with querySelector being one of the most versatile methods. This method allows us to select elements by:

  • Tag name
  • Class
  • ID
// Selecting by tag nameconst h1 = document.querySelector('h1');console.log(h1?.textContent);
// Selecting by classlet title: HTMLHeadingElement = document.querySelector('.title') as HTMLHeadingElement;console.log(title?.textContent);
// Selecting by IDconst message = document.querySelector('#message') as HTMLInputElement;console.log(message.placeholder);

It is important to note that when using querySelector, TypeScript cannot automatically infer the type of element we are selecting. Therefore, it is advisable to use the type assertion(as HTMLHeadingElement) to tell TypeScript what type of element we are expecting.

Handling potentially null values

When we select elements from the DOM, there is always the possibility that the element does not exist. TypeScript helps us handle these cases with the optional chaining operator (?):

// The ? sign indicates that h1 could be nullconsole.log(h1?.textContent);

This operator allows us to access properties of an object that could be null without causing runtime errors.

How to optimize the workflow with TypeScript and HTML?

Working with TypeScript and HTML involves a constant cycle of:

  1. Writing TypeScript code
  2. Compiling to JavaScript
  3. Verifying results in the browser

This process can become tedious if we have to manually run the compiler every time we make a change. Fortunately, TypeScript offers a "watch" mode that automates this process.

Using watch mode for automatic compilation

TypeScript's watch mode monitors changes to our .ts files and automatically compiles them when it detects modifications:

tsc main.ts --watch# or the shorthandtsc main.ts -w

With this command, TypeScript will watch for any changes to our file and compile it instantly, allowing us to focus on writing code without worrying about the compilation process.

Integrating the terminal into the editor

To make our workflow even more efficient, we can use the terminal integrated into Visual Studio Code:

  1. Open a new terminal in VS Code (Terminal > New Terminal).
  2. Navigate to our project folder
  3. Execute the tsc command with the --watch option.

This allows us to have everything in a single window: our code, the terminal and, in another browser tab, the results.

What considerations should we have when working with the DOM in TypeScript?

When manipulating the DOM with TypeScript, there are some important considerations to keep in mind to avoid errors and take full advantage of static typing.

Correct HTML element typing

TypeScript provides specific interfaces for each type of HTML element:

  • HTMLHeadingElement for heading elements (h1, h2, etc.).
  • HTMLInputElement for input elements
  • HTMLButtonElement for buttons
  • And many more

Using the correct type allows us to access specific properties of each element without compilation errors:

// Accessing input-specific propertiesconst inputElement = document.querySelector('#message') as HTMLInputElement;console.log(inputElement.placeholder); // Input-specific propertyconsole.log(inputElement.value); // Other specific property.

Loading the script at the right time

It is crucial to make sure that our script is loaded after the DOM is fully loaded. There are two main ways to accomplish this:

  1. Using the defer attribute in the script tag:
<script src="main.js" defer></script>
  1. Place the script tag at the end of the body:
<body> <!-- HTML content --> <script src="main.js"></script></body></body>

Both options ensure that the DOM is available when our code tries to access it.

Integrating TypeScript with HTML gives us a powerful and safe way to manipulate the DOM, taking advantage of static typing to catch errors early and improve the quality of our code. With practice, the workflow between editor, terminal and browser becomes natural, allowing us to develop more robust and maintainable web applications.

Have you experimented with TypeScript to manipulate the DOM? Share your experiences and doubts in the comments section to continue learning together.

Contributions 1

Questions 0

Sort by:

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

como dato curioso: Se puede cambiar un tipo amplio a un tipo m谩s espec铆fico ```js let elemento: HTMLElement; elemento = document.querySelector('button') as HTMLButtonElement; // De HTMLElement a HTMLButtonElement ```