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
13 Hrs
23 Min
36 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

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

15/26
Resources

Modularization in TypeScript is an essential practice for keeping your code organized, scalable and easy to maintain. Breaking your code into smaller modules not only improves readability, but also makes it easier to detect and correct errors, allowing you to create more robust and professional applications.

Why avoid monoliths in your code?

A "monolith" in programming refers to large volumes of code concentrated in a single file. This practice is generally discouraged for several reasons:

  • Increased likelihood of errors: the more lines of code a file has, the more likely it is that errors will appear.
  • Difficulty in locating problems: In large files, finding and correcting errors becomes a much more complex task.
  • Complicated maintenance: Updating or modifying specific functionality requires navigating large blocks of code.
  • Limited collaboration: Working as a team becomes difficult when multiple developers need to modify the same file.

The solution to these problems is modularization - splitting your code into smaller files with specific responsibilities.

How to create and use modules in TypeScript?

Implementing modules in TypeScript is straightforward and follows a similar pattern to the classes we already know. Let's see how to create our first modules:

Creating a calculator module.

First, we create a file called calculator.ts that will contain basic mathematical functions:

export function sum(num1: number, num2: number) { return num1 + num2;}
export function subtraction(num1: number, num2: number) { return num1 - num2;}
export function multiplication(num1: number, num2: number) { return num1 * num2;}
export function division(num1: number, num2: number) { return num1 / num2;}
export const pi = 3.1416;

The export keyword is critical here, as it indicates that these elements can be imported from other files. You can export:

  • functions.
  • Constants
  • Variables
  • Classes
  • Interfaces
  • Types

Importing and using the module

Once our module is created, we can use it from another file, for example, main.ts:

import { addition, subtraction, multiplication, division, pi } from './calculator';
console.log(addition(10, 154)); // Result: 164console.log(subtraction(1, pi)); // Using the imported constant.

When compiling main.ts with the tsc main.ts command, TypeScript will automatically compile calculator.ts as well because it is being referenced. This generates the corresponding JavaScript files that we can run with Node.js:

node main.js

The result will show the values calculated by our imported functions.

Benefits of modularization

Modularization offers multiple advantages:

  • More organized code: Each file has a specific responsibility.
  • Better maintainability: You can modify one module without affecting others.
  • Reusability: You can import the same functions in different parts of your application.
  • Teamwork: Different developers can work on different modules simultaneously.
  • Easier testing: It is easier to write unit tests for small and specific modules.

When and how to refactor your code into modules?

Refactoring is the process of restructuring existing code without changing its external behavior. It is a recommended practice to improve code quality.

To refactor your code into modules:

  1. Identify groups of related functionality in your current code.
  2. Extract those functionalities to separate files.
  3. Export the necessary functions, constants or classes.
  4. Import these elements into the files where they are needed.
  5. Test that everything is still working correctly.

It is important to mention that you don't need to start with modules. You can first develop a large file that meets your goal and, once it works correctly, refactor it into smaller modules.

Modularization is a fundamental skill for any TypeScript developer looking to create maintainable and scalable applications. Implementing this practice from the beginning of your projects or refactoring existing code will help you build more robust and professional solutions.

Have you tried modularizing any of your projects? Share in the comments how it has improved your code organization and what challenges you have encountered in the process.

Contributions 2

Questions 0

Sort by:

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

Al importar un objeto o función en TypeScript, no es necesario especificar la extensión del archivo (como ".ts") debido a que el compilador de TypeScript automáticamente resuelve las extensiones durante el proceso de compilación. Este comportamiento es parte de la configuración estándar del sistema de módulos de TypeScript, lo que facilita la escritura del código y mejora la legibilidad. Además, evita errores comunes relacionados con la carga de archivos. Esto se relaciona con la fragmentación y organización del código en módulos, como se discutió en la clase.
La clase se centra en la importación y exportación de módulos en TypeScript, un superset de JavaScript que permite añadir tipado fuerte al código. Se explica cómo dividir el código en archivos más pequeños, lo que facilita la organización, la legibilidad y la escalabilidad del proyecto. Se crean funciones como suma, resta, multiplicación y división en un módulo separado y se importan en un archivo principal. Se destaca la importancia de evitar monolitos y refactorizar el código en módulos para una mejor gestión y mantenimiento.