Funciones
## Objetivos de Aprendizaje
- Escribir parametros de funcion tipados
- Definir tipos de retorno
- Dominar funciones flecha
- Usar tipos de funcion
- Trabajar con parametros opcionales y por defecto
## Sintaxis Basica de Funciones
### Funcion Nombrada
```typescript
function add(a: number, b: number): number {
return a + b;
}
let result: number = add(5, 3); // 8
```
### Expresion de Funcion
```typescript
const multiply = function(a: number, b: number): number {
return a * b;
};
```
## Tipos de Parametros
### Parametros Tipados
```typescript
function greet(name: string): string {
return `Hola, ${name}!`;
}
greet("Alice"); // "Hola, Alice!"
// greet(123); // Error: Argumento de tipo 'number'
```
### Multiples Parametros
```typescript
function introduce(name: string, age: number): string {
return `${name} tiene ${age} anios`;
}
```
## Tipos de Retorno
### Tipo de Retorno Explicito
```typescript
function getRandomNumber(): number {
return Math.random();
}
// Retorno void
function logMessage(msg: string): void {
console.log(msg);
}
```
### Tipo de Retorno Inferido
```typescript
function add(a: number, b: number) {
return a + b; // TypeScript infiere: number
}
```
## Parametros Opcionales
Parametros con `?` son opcionales:
```typescript
function greet(name?: string): string {
if (name) {
return `Hola, ${name}!`;
}
return "Hola!";
}
greet("Bob"); // "Hola, Bob!"
greet(); // "Hola!"
```
### Opcional vs Undefined
```typescript
// Ambos son opcionales
function example(a?: string, b?: number) { }
// Con undefined explicito
function example2(a: string | undefined) { }
```
## Parametros por Defecto
Valores por defecto cuando no se proporciona argumento:
```typescript
function greet(name: string = "Invitado"): string {
return `Hola, ${name}!`;
}
greet("Alice"); // "Hola, Alice!"
greet(); // "Hola, Invitado!"
```
### Por Defecto con Tipo
```typescript
function createUser(name: string, role: string = "usuario"): { name: string; role: string } {
return { name, role };
}
```
## Parametros Rest
Recoger argumentos restantes:
```typescript
function sum(...numbers: number[]): number {
return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3); // 6
sum(1, 2, 3, 4, 5); // 15
```
### Rest con Parametros Regulares
```typescript
function logMessage(level: string, ...args: string[]): void {
console.log(`[${level}]`, ...args);
}
logMessage("INFO", "Servidor", "iniciado"); // [INFO] Servidor iniciado
```
## Funciones Flecha
### Sintaxis
```typescript
const add = (a: number, b: number): number => {
return a + b;
};
```
### Forma Abreviada
```typescript
const add = (a: number, b: number): number => a + b;
const square = (x: number): number => x * x;
const greet = (name: string): string => `Hola, ${name}!`;
```
### Sin Parametros
```typescript
const getRandom = (): number => Math.random();
const logTimestamp = (): void => {
console.log(Date.now());
};
```
## Funciones Flecha y `this`
### Problema con Funciones Regulares
```typescript
class Timer {
seconds: number = 0;
start() {
// 'this' se pierde
setInterval(function() {
this.seconds++; // 'this' no es Timer
}, 1000);
}
}
```
### Solucion con Funciones Flecha
```typescript
class Timer {
seconds: number = 0;
start() {
// 'this' se preserva
setInterval(() => {
this.seconds++;
}, 1000);
}
}
```
## Tipos de Funcion
### Anotacion de Tipo
```typescript
let myFunction: (a: number, b: number) => number;
myFunction = (x, y) => x + y;
myFunction = (x, y) => x * y;
// myFunction = "hola"; // Error
```
### En Parametros de Funcion
```typescript
function operate(a: number, b: number, op: (x: number, y: number) => number): number {
return op(a, b);
}
let result = operate(10, 5, (x, y) => x + y); // 15
result = operate(10, 5, (x, y) => x - y); // 5
```
## Tipos de Callback
```typescript
function fetchData(
callback: (data: string) => void,
errorCallback: (error: Error) => void
): void {
// Exito
callback("Datos recibidos");
// O error
// errorCallback(new Error("Fallo"));
}
fetchData(
(data) => console.log(data),
(err) => console.error(err)
);
```
## Tipos de Retorno y Genericos
```typescript
function firstElement(arr: T[]): T | undefined {
return arr[0];
}
let num = firstElement([1, 2, 3]); // number | undefined
let str = firstElement(["a", "b"]); // string | undefined
```
## Funciones Sobrecargadas
Multiples firmas de funcion:
```typescript
function reverse(str: string): string;
function reverse(arr: string[]): string[];
// Implementacion
function reverse(strOrArr: string | string[]): string | string[] {
if (typeof strOrArr === "string") {
return strOrArr.split("").reverse().join("");
}
return strOrArr.reverse();
}
reverse("hola"); // "aloh"
reverse(["a", "b", "c"]); // ["c", "b", "a"]
```
## Funciones Constructor
```typescript
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
function createPerson(name: string, age: number): Person {
return new Person(name, age);
}
let person = createPerson("Alice", 30);
```
## Sintaxis de Metodos
### En Clases
```typescript
class Calculator {
add(a: number, b: number): number {
return a + b;
}
static multiply(a: number, b: number): number {
return a * b;
}
}
let calc = new Calculator();
calc.add(2, 3); // 5
Calculator.multiply(2, 3); // 6
```
## Retorno Void en Callbacks
```typescript
function executeCallback(callback: () => void): void {
console.log("Antes del callback");
callback();
console.log("Despues del callback");
}
executeCallback(() => {
console.log("Callback ejecutado!");
});
```
## Retorno never
```typescript
function fail(message: string): never {
throw new Error(message);
}
function processValue(value: string | number): string {
if (typeof value === "string") {
return `Cadena: ${value}`;
}
if (typeof value === "number") {
return `Numero: ${value}`;
}
fail("Tipo de valor inesperado");
}
```
## Resumen
- Las funciones pueden tener parametros y tipos de retorno explicitos
- Usar `?` para parametros opcionales
- Los parametros por defecto proporcionan valores de respaldo
- Los parametros rest (`...args`)搜集 multiplos argumentos
- Funciones flecha: `(x, y) => x + y`
- Las funciones flecha preservan el contexto de `this`
- Tipos de funcion: `(a: number, b: number) => number`
- Usar `void` cuando la funcion no retorna un valor
- Usar `never` para funciones que nunca retornan
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →