Language: EN

typescript-funciones-arrow

Arrow Functions in TypeScript

TypeScript supports anonymous functions and arrow functions, which are more concise ways of writing functions.

Anonymous Functions

Anonymous functions are functions without a name, commonly used as arguments to other functions.

const greet = function(name: string): void {
    console.log(`Hello ${name}.`);
};

These functions (as their name suggests) do not have an assigned name and are used in a variety of contexts. Especially when a temporary or short-lived function is needed.

Arrow Functions

Arrow functions are a compact syntax for defining functions in JavaScript and TypeScript. They are characterized by using the => syntax and have several advantages over traditional functions, especially in terms of handling this.

Arrow functions allow you to write functions more concisely and readably, especially when it comes to short functions or single-line functions.

The basic syntax of an arrow function is as follows:

(param1, param2, ..., paramN) => {
    // function body
}

For example,

const greet = (name: string): void => {
    console.log(`Hello ${name}.`);
};

For functions with a single parameter, parentheses can be omitted:

param => {
    // function body
}

If the function consists of a single expression, the curly braces and the return keyword can be omitted:

(param1, param2) => param1 + param2

Arrow functions are especially useful in contexts where you need to preserve the this context of the enclosing function, as they use the this context from the environment in which they were created.