EN
TypeScript - arrow functions
0 points
In this article, we would like to show you how to create and use arrow functions in TypeScript.
Quick solution:
xxxxxxxxxx
1
const functionName = (): type => {
2
// function body here
3
};
with arguments:
xxxxxxxxxx
1
const functionName = (arg1: type, arg2: type): type => {
2
// function body here
3
};
without parentheses:
xxxxxxxxxx
1
const multiply = (x: number): number => x * 2; // example function that multiplies by 2
In this example, we create a simple arrow function with no arguments.
xxxxxxxxxx
1
const helloWorld = (): void => {
2
console.log('Hello World!');
3
};
4
5
helloWorld();
Output:
xxxxxxxxxx
1
Hello World!
In this example, we create a simple arrow function that displays its arguments in the console.
xxxxxxxxxx
1
type argumentType = number | string;
2
3
const display = (x: argumentType, y: argumentType): void => {
4
console.log('Argument1 = ' + x);
5
console.log('Argument2 = ' + y);
6
};
7
8
9
// Usage example:
10
11
display(1, 2);
12
display('a', 'b');
Output:
xxxxxxxxxx
1
Argument1 = 1
2
Argument2 = 2
3
Argument1 = a
4
Argument2 = b
In this example, we create an arrow function with no parentheses. The function multiplies the given number by 2
. Notice that in this kind of function you don't need the return
statement.
xxxxxxxxxx
1
const multiply = (x: number): number => x * 2;
2
3
4
// usage example
5
6
const result1: number = multiply(1);
7
const result2: number = multiply(2);
8
9
console.log(result1); // 2
10
console.log(result2); // 4
Output:
xxxxxxxxxx
1
2
2
4
In this example, we present a comparison of the arrow function with a normal function.
Arrow function solution:
xxxxxxxxxx
1
const multiply = (x: number): number => x * 2;
2
3
4
// Usage example:
5
6
const result: number = multiply(1);
7
console.log(result); // 2
is equal to:
xxxxxxxxxx
1
const multiply = function (x: number): number {
2
return x * 2;
3
};
4
5
6
// Usage example:
7
8
const result: number = multiply(1);
9
console.log(result); // 2