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
57 Min
3 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

Declaración de funciones, tipado de parámetros y valores de retorno

6/26
Resources

TypeScript programming becomes more powerful when you master its functions and methods, fundamental elements that allow you to organize and reuse code efficiently. These structures are the backbone of any well-designed application, allowing you to create elegant and maintainable solutions. Let's see how to implement and leverage these essential tools in your projects.

How to create basic functions in TypeScript?

Functions in TypeScript follow a clear structure that allows you to define their behavior and the data they handle. To create a basic function, we need to use the reserved word function, followed by the name we want to assign to it and the parameters it will receive.

A simple function that does not return any value ( void type) can be implemented like this:

function printMessage(message: string): void { console.log(message);}
printMessage("Hello, I am a message");

In this example:

  • We define a function named printMessage.
  • Receives a string parameter named message
  • It does not return any value ( void type)
  • Inside the function, we use console.log to show the message received.
  • Finally, we invoke the function by passing a text string to it

To run this code, we must first compile it with the tsc command and then run it with node:

tsc metodos.tsnode metodos.js

The result will be the printout of the message "Hello, I am a message" in the console.

How to create functions that return values?

One of the main advantages of functions is their ability to process data and return results. In TypeScript, we can clearly specify the type of data that our function will return.

Let's look at an example of a function that adds two numbers together:

function sum(number1: number, number2: number): number { return number1 + number2;}
let result: number;result = sum(5, 10);console.log("Your result is", result);

In this case:

  • The function sum receives two parameters of type number.
  • We specify that it will return a value of type number.
  • We create a result variable to store the returned value.
  • We invoke the function with the values 5 and 10
  • Display the result in the console

TypeScript's strict typing helps us prevent errors by making sure that the values we pass and receive are of the correct type.

Alternatives for using the result of a function

There are different ways to use the value returned by a function:

  1. Assigning it to a variable:

    let result: number = sum(5, 10);console.log("Your result is", result);
  2. Using it directly:

    console.log("Your result is", sum(5, 10));

The first option usually makes the code more readable, especially when we need to use the result in multiple places or when the function call is complex.

Why are methods important in TypeScript?

Methods and functions in TypeScript offer significant advantages over traditional JavaScript thanks to the type system:

  1. Greater clarity: explicit typing makes it easier to understand what a function expects to receive and what it will return.

  2. Early error detection: The TypeScript compiler can identify problems before executing code.

  3. Better documentation: Types act as a form of documentation built into the code.

  4. Better auto-completion: Editors such as Visual Studio Code can provide more accurate suggestions.

  5. Safer refactoring: When changing a function, the compiler will help you identify all the places that need to be updated.

Using well-typed functions establishes a logical sequence in your application workflow, making the code more maintainable and less error-prone.

Functions and methods are fundamental tools in any programming language, and TypeScript enhances them significantly with its type system. Mastering their creation and use will allow you to develop more robust and maintainable applications. Have you experimented with more complex functions in TypeScript? Share your experiences and questions in the comments.

Contributions 3

Questions 0

Sort by:

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

🔦 Aunque Función y metodo son similares, tienen unas sutiles diferencias: **Función:** Bloque de código que puede existir, por sí solo, para realizar una acción específica. **Método:** Función asociada a una clase u objeto, y opera sobre sus propiedades, usan la palabra clave this
Para declarar funciones en TypeScript, utilizas la palabra reservada `function`, seguida del nombre de la función, paréntesis para los parámetros y llaves para el cuerpo de la función. Puedes especificar tipos para los parámetros y el valor de retorno. Aquí hay un ejemplo simple: ```typescript function sumar(numero1: number, numero2: number): number { return numero1 + numero2; } ``` En este caso, `numero1` y `numero2` son parámetros de tipo `number`, y la función también especifica que retornará un valor de tipo `number`. Si deseas crear una función que no retorne un valor, puedes usar `void` como tipo de retorno: ```typescript function imprimeMensaje(mensaje: string): void { console.log(mensaje); } ``` En este caso, `mensaje` es un parámetro de tipo `string`, y la función no retorna ningún valor. Recuerda que al usar TypeScript, el tipado fuerte te ayuda a evitar errores y a hacer tu código más comprensible y mantenible.
Les dejo algo que se puede hacer tomándooslo en cuenta el curso anterior de TS y viendo la magia que tiene este lenguaje: ```js enum NumeroPredef { Uno = 1, Dos = 2, Tres = 3, Cuatro = 4, Cinco = 5, } type Numeros = { num1: number; num2: NumeroPredef; } function sum(nums: Numeros):number { return nums.num1 + nums.num2; } console.log(sum({ num1: 10, num2: NumeroPredef.Cuatro, })); ```