Fundamentos de TypeScript
驴Qu茅 es TypeScript y por qu茅 usarlo?
Instalaci贸n de Node.js y TypeScript CLI, configuraci贸n de tsconfig.json
Tipos primitivos: string, number, boolean, null, undefined de Typescript
Tipos especiales: any, unknown, never, void de TypeScript
Arrays, Tuplas, Enums en TypeScript
Funciones e Interfaces
Declaraci贸n de funciones, tipado de par谩metros y valores de retorno
Par谩metros opcionales, valores por defecto y sobrecarga de funciones
Creaci贸n y uso de interfaces de TypeScript
Propiedades opcionales, readonly, extensi贸n de interfaces en TypeScript
Clases y Programaci贸n Orientada a Objetos
Creaci贸n de clases y constructores En TypeScript
Modificadores de acceso (public, private, protected) en Typescript
Uso de extends, sobreescritura de m茅todos en TypeScript
Introducci贸n a Gen茅ricos en Typescript
Restricciones con extends, gen茅ricos en interfaces
M贸dulos y Proyectos
Importaci贸n y exportaci贸n de m贸dulos en TypeScript
Agregando mi archivo de Typescript a un sitio web
Configuraci贸n de un proyecto Web con TypeScript
Selecci贸n de elementos, eventos, tipado en querySelector en TypeScript
Crear un proyecto de React.js con Typescript
Crea un proyecto con Angular y Typescript
Crea una API con Typescript y Express.js
Conceptos Avanzados
Introducci贸n a types en TypeScript
Implementaci贸n de Decoradores de TypeScript
Async/await en Typescript
Pruebas unitarias con Jest y TypeScript
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
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.
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:
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:
// 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.
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.
Working with TypeScript and HTML involves a constant cycle of:
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.
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.
To make our workflow even more efficient, we can use the terminal integrated into Visual Studio Code:
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.
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.
TypeScript provides specific interfaces for each type of HTML element:
HTMLHeadingElement
for heading elements (h1, h2, etc.).HTMLInputElement
for input elementsHTMLButtonElement
for buttonsUsing 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.
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:
defer
attribute in the script tag:<script src="main.js" defer></script>
<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
Want to see more contributions, questions and answers from the community?