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:

2 Días
17 Hrs
45 Min
22 Seg
Curso de TypeScript

Curso de TypeScript

Nicolas Molina

Nicolas Molina

Retorno de funciones

18/24
Resources

In TypeScript we can specify the data type of the value that a function will return or indicate if no data will be returned:

Typed returns in TypeScript

The return type will be specified after the parentheses containing the function arguments:

  1. Void: functions with no return
    This type of function executes certain instructions, but does not return any data. These are known as void functions. They are defined as follows:
//TypeScriptfunction printName(yourName: string): void {  console.log(`Hello ${yourName}`); }
  1. Functions with return
    On the other hand, if in the function we will return some value, we can specify the data type of it:
//TypeScriptfunction sum(a: number, b: number): number {  return a + b; }function helloWorld(): string {  return "Hello, World!"; }

Also returns can be more than one data type:

//TypeScriptfunction returnMajor(a: number, b: number): number | string {  if(a > b){ // Return a number return a; } else if( b > a ) { // Return a number return b; } else { // Return a string return `The numbers ${a} and ${b} are equal`; } } }

TypeScript also infers this

If we do not indicate in our function declaration the return type, TypeScript, as with variables, can infer it depending on whether you return data (be it string, number, etc.) or if nothing is returned ( void type).

Contributed by: Martín Álvarez.

Contributions 17

Questions 5

Sort by:

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

Resumen de la clase

En TS podemos especificar que tipo de dato retorna la función e incluso podemos indicar cuando esa funcion no retorna nada.

// Retornando un string
function joinName(fName: string, lName: string): string {
 return `${fName} ${lName}`
}

// Funcion sin retorno
function printName(name: string): void {
  console.log(name)
}

El curso de manipulacion de arrays es buenisimo, lo uso de referencia seguido

Lo mismo pero con el método reduce:

  const calcTotal = (prices: number[]): number => {
    return prices.reduce((total, price) => total + price, 0);
  };
  console.log(calcTotal([10, 20, 30])); // 60

Les comparto mis apuntes. 😄

Void

Normalmente, lo usamos para funciones de efecto secundario, funciones que llaman a otras funciones.

Lo utilizamos para funciones que no tengan un retorno, que no retornen ningún tipo de valor.

Sintaxis tipo explícito

Funciones declarativas

function functionName (parameters: dataTypes): dataTypes { statements }

Arrow functions

const functionName = (parameters: dataTypes): dataTypes => { statements }

Código de la clase

(() => {
    const calcTotal = (prices: number[]): string => {
        let total = 0;
        prices.forEach(item => total += item);
        return total.toString();
    }

    // const rta = calcTotal([1, 2, 1, 1, 1]);
    // console.log(rta);

    const printTotal = (prices: number[]): void => {
        const rta = calcTotal(prices);
        console.log(`El total es ${rta}`);
    }

    const rta = printTotal([1, 2, 1, 1, 1]);
})();

Esta super interesante esto del tipo de dato que queremos retornar en una funcion, entonces podemos decirle a una función que retorne algún Literal Types de esta manera:

  type SizeTshirt = "M" | "L" | "XG" | "S";
  type User = { name: string; user: string; size: SizeTshirt };

  const greeting = (user: string, name: string, size: SizeTshirt): User => {
    return {
      user,
      name,
      size,
    };
  };

Aqui esta la url del github en la rama de esta clase:
https://github.com/platzi/curso-typescript-fundamentos/tree/16-step

Esta interesante el curso 😄

  const calcTotal =(prices: number[])=> {
    let total = 0;
    total = prices.reduce((e,i)=>e+i);
    console.log(`El total es: ${total}`); 
    return total;
  };

  const Nguardado = calcTotal([12,34,31,4,134])
  console.log(Nguardado+1);

Otras soluciones alternativas

Ejercicio de la clase:

(() => {
  const calcTotal = (prices: number[]): string => {
    let total = 0;
    prices.forEach((item) => {
      total += item;
    });
    return total.toString();
  }

  const printTotal = (prices: number[]): void => {
    const rta = calcTotal(prices);
    console.log(`El total es ${rta}`);
  }

  printTotal([1, 2, 3, 5, 6]);
})();

💡 Un dato interesante es que en JavaScript las funciones que no retornan un valor, implícitamente retortan undefined.
Sin embargo, void y undefined no son lo mismo en TypeScript como hemos podido ver en las clases de este curso.

Para quien pensó en como hacer un clousure con Typescript esto te puede servir. Este aporte fue posible gracias al curso profesional de Javascript.

function newClousure (a: number): (b: number) => number {

  return function(b) {
    return a + b;
  }
}

Con arrow functions

const newClousure = (a: number): (b: number, c: string) => number => {
  return (b, c) => {
    return 5;
  }
}

aquí las tengo :v

❤️|

Como le menciono Nico podemos usar el reduce para hacerlo de una manera mas elegante les dejo el código que desarrolle usando el reduce adicionalmente al usar arrow functions si nuestra función solo realiza una acción podemos escribir una sola linea de código evitando poner las llaves {} después de definir la función

(() => {
  const calTotal = (prices:  number[]): string =>
   prices.reduce((sum, price) => sum + price)
   .toString();

   const printTotal = (prices: number[]): void =>
   console.log(calTotal(prices));

   printTotal([1,2,3]);

})();
puedes hacer que una función retorne de manera inferida o puede hacer lo de manera explicita poniendo `:` después de los parámetros `()` antes de poner la arrow function `⇒` const calcularPrecios = (prices: number\[]): number => { let total = 0; prices.forEach((price) => { total += price; }); // no puede retornar un string return total; } const rst = calcularPrecios(\[100,200,300,400]); console.log(rst) Las funciones que no retornan nada van a ser de tipo `void` const printTotal = (prices: number\[]) => { const rst = calcularPrecios(prices); console.log(`El total es ${rst}`) } // la funcion es void porque no tiene retorno printTotal(\[100,200,300,400]); o tambien puede obligarla a ser void

1-ejemplo: ![](https://static.platzi.com/media/user_upload/image-2e1f49f1-bf0b-47fe-932e-5da87b7da419.jpg) 2- ejemplo: ![](https://static.platzi.com/media/user_upload/image-4ec47bd8-a50e-4c89-812c-75e01e9e1e3f.jpg)