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
46 Min
13 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

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

7/26
Resources

Parameters in TypeScript functions offer extraordinary flexibility that allows us to optimize our code and make it more efficient. By mastering the different types of parameters, we can create versatile methods that adapt to multiple scenarios without the need to duplicate code. This capability not only improves readability but also significantly reduces development time.

How do we make our functions more flexible with special parameters?

When working with TypeScript, we can make our functions much more adaptable by using different types of parameters. This allows us to write less code that performs more tasks, resulting in more maintainable and efficient applications.

Optional parameters: How to implement them correctly?

Optional parameters allow us to define arguments that may or may not be provided when calling a function. To indicate that a parameter is optional, we simply add a question mark (?) after the parameter name.

Let's see a practical example:

function greet(name: string, greeting?: string): string { if (greeting) { return `${greeting}, ${name}!`; } else { return `Hello, ${name}`; } }}
console.log(greet("Amin"));console.log(greet("Amin", "Good morning"));

When executing this code, we will get:

  • "Hello, Amin" (when we do not provide the greeting).
  • "Good morning, Amin!" (when we do provide the greeting).

The main advantage of optional parameters is that they save us from having to create multiple versions of the same function to handle different cases. A single function can adapt to different situations depending on the arguments it receives.

Multiple parameters: How to handle a variable number of arguments?

Multiple parameters (or rest parameters) allow us to pass an indefinite number of arguments to a function. They are indicated by three dots (....) before the parameter name.

function sumAll(...numbers: number[]): number { return numbers.reduce((accumulator, value) => accumulator + value, 0);}
console.log(`Theresult of adding all is ${sumAll(1, 2, 3, 4, 5)}`);

This code will add all the provided numbers (1+2+3+4+5) and display "The result of adding all is 15".

The reduce method used in this example is an elegant way to process all the elements of an array without using a foreach loop. This method accumulates the values as it cycles through the array.

Multiple parameters can be tricky at first, but with practice they become a very powerful tool for creating flexible functions that can handle different amounts of data.

Defaults: How to set defaults?

Defaults allow us to assign a default value to a parameter in case none is provided when calling the function.

function goodbye(name: string, goodbye: string = "Goodbye"): string { return `${goodbye}, ${name}`;}
console.log(goodbye("Amin"));console.log(goodbye("Amin", "See you later"));

When executing this code, we will get:

  • "Goodbye, Amin" (using the default value).
  • "See you later, Amin" (overwriting the default value).

The key difference between optional parameters and default values is that the former may not be present, while the latter will always have a value, either the one provided or the default.

Why optimize our functions with these parameters?

Implementing these types of parameters in our functions allows us to:

  • Simplify our code: instead of writing multiple functions for different cases, we can create a single, more versatile function.
  • Optimize development time: less code means less time writing and debugging.
  • Improve readability: more concise code is generally easier to understand and maintain.

Mastering these concepts in TypeScript helps us write more elegant and efficient code, taking full advantage of the language's capabilities to create robust and maintainable applications.

Special parameters in TypeScript are powerful tools that every developer should know and use. Have you implemented any of these types of parameters in your projects? Which one has been most useful to you? Share your experience in the comments.

Contributions 5

Questions 0

Sort by:

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

## 📐 **Sobrecarga de funciones en TypeScript** La **sobrecarga de funciones** nos permite declarar **múltiples versiones** de una misma función con diferentes **firmas de entrada**, pero una sola implementación. 🔹 **Sintaxis:** * Primero declaramos las firmas sobrecargadas. * Luego implementamos la función con lógica para cubrir todos los casos. 📌 **Ejemplo clásico:** ```js // Firmas de sobrecarga function combinar(a: string, b: string): string; function combinar(a: number, b: number): number; // Implementación única function combinar(a: string | number, b: string | number): string | number { if (typeof a === "string" && typeof b === "string") { return a + b; // Concatenación } if (typeof a === "number" && typeof b === "number") { return a + b; // Suma numérica } throw new Error("Tipos incompatibles"); } console.log(combinar("Hola", " Mundo")); // "Hola Mundo" console.log(combinar(10, 20)); // 30 ```// Firmas de sobrecarga function combinar(a: string, b: string): string; function combinar(a: number, b: number): number; // Implementación única function combinar(a: string | number, b: string | number): string | number { if (typeof a === "string" && typeof b === "string") { return a + b; // Concatenación } if (typeof a === "number" && typeof b === "number") { return a + b; // Suma numérica } throw new Error("Tipos incompatibles"); } console.log(combinar("Hola", " Mundo")); // "Hola Mundo" console.log(combinar(10, 20)); // 30 ⚠️ TypeScript **no permite múltiples implementaciones**, solo múltiples **firmas**.
El titulo dice sobre carga de funciones y en ningún momento del video se toca este tema
Para la sobrecarga de funciones les dejo un ejemplo practico ```js type User = { id: number; name: string }; // Base de datos simulada const users: User[] = [ { id: 1, name: "Osorio" }, { id: 2, name: "Daniela" } ]; // Firmas de sobrecarga function findUser(query: number): User | undefined; function findUser(query: string): User | undefined; // Implementación function findUser(query: number | string): User | undefined { if (typeof query === "number") { return users.find(user => user.id === query); } else { return users.find(user => user.name === query); } } // Uso console.log(findUser(1)); // { id: 1, name: "Osorio" } console.log(findUser("Daniela")); // { id: 2, name: "Daniela" } ```
TypeScript es hermoso cuando lo entiendes, ejemplo: ```js enum NumerosElegir { UNO = 1, DOS = 2, TRES = 3, CUATRO = 4, CINCO = 5, } type Multiplicador = { num1: number; num2: NumerosElegir; } function sumarTodo(...nums:number[]):number { return nums.reduce((a, b) => a + b, 0); } function Multiplicar(numero:Multiplicador):number { return numero.num1 * numero.num2; } function decirNumero(resultado:number, fraseInicial: string = "El resultado es:", fraseFinal?: string):void { console.log(`${fraseInicial} ${resultado} ${fraseFinal ? fraseFinal : ""}`); } const sumaTotal = sumarTodo(1,2,3,4,5,6,7,8,9,10,20) const multiTotal = Multiplicar({num1: sumaTotal, num2: NumerosElegir.CUATRO}) const decirSuma = decirNumero(sumaTotal, "El resultado de la suma es:", "y eso es todo"); const decirMulti = decirNumero(multiTotal); ```
En TypeScript, la sobrecarga de funciones permite definir múltiples firmas para una función, pero solo una implementación real. Es útil para crear funciones que pueden recibir diferentes tipos o combinaciones de parámetros y devolver distintos resultados según el caso. Ejemplo de sobrecarga de funciones en TypeScript Explicación `// Firmas de la función` `function saludar(nombre: string): string;` `function saludar(nombres: string[]): string;` `// Implementación de la función` `function saludar(param: string | string[]): string {` ` if (typeof param === "string") {` `` return `¡Hola, ${param}!`;`` ` } else {` `` return `¡Hola a todos: ${param.join(", ")}!`;`` ` }` `}` `// Uso de la función` `console.log(saludar("Juan")); // ¡Hola, Juan!` `console.log(saludar(["Ana", "Luis"])); // ¡Hola a todos: Ana, Luis!` Es importante recordar que la implementación real de la función debe coincidir con las firmas declaradas, y que la lógica dentro de la función debe manejar correctamente los diferentes tipos de entrada.