Open In App

Explain the arrow function syntax in TypeScript

Improve
Improve
Like Article
Like
Save
Share
Report

In this article we will try to understand how use the basic arrow function syntax in TypeScript. Arrow functions are basically the shorter way provided to all the users in order to implement the long/traditional function syntax in a much more shorter manner with ease.

Arrow functions as implemented in JavaScript (ES6), will be implemented in a similar manner in TypeScript also; the only addition in the original syntax as provided by ES6 here in TypeScript is the addition of data types or return types along with the function syntax and also along with the arguments passed inside that function.

Syntax: Following syntax we may use to implement Arrow functions in TypeScript.

let function_name = (
    parameter_1 : data_type, 
    ...
) : return_type => {
    ...
}

Now things till here might seems little bit ambiguous, so lets make things more clear by visualizing the above syntax using some of the following illustrated examples (in order to run these examples either search for online typescript compiler or install typescript in your local PC and compile the codes effectively)-

Example 1: In this example we will simply create a function that returns a string name which is passed inside the function as a parameter itself using the above illustrated syntax.

Javascript




let display_name = (name : string) : string => {
    return name;
}
  
// Function call
console.log(display_name("GeeksforGeeks"));


Output:

GeeksforGeeks

Example 2: In this example we will simply add two integers using a function in which we will pass on two integers of data type number and will also specify return type of function as number and print the addition result in browser’s console.

Javascript




let addition = (number1 : number, number2 : number) : number => {
    return number1 + number2;
}
  
// Function call
console.log(addition(50, 90));
console.log(addition(90, 90));
console.log(addition(100, 90));


Output:

140
180
190

Example 3: In this example we will implement a function whose return type is string consisting of three different data types variables which will print their specified results.

Javascript




let users_details = (
    rollno: number, 
    name: string, 
    scores_obtained: number[]
) : string => {
    let user_detail : string = rollno + "- " 
        + name + "- "+ scores_obtained;
    return user_detail;
}
  
// Function call
console.log(users_details(1, "ABC", [10 , 20 , 30]));
console.log(users_details(2, "APPLE", [50 , 20 , 30]));
console.log(users_details(3, "MANGO", [70 , 90 , 80]));


Output:

1- ABC- 10,20,30
2- APPLE- 50,20,30
3- MANGO- 70,90,80

Reference: https://www.typescriptlang.org/docs/handbook/functions.html#this-and-arrow-functions



Last Updated : 16 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads