TypeScript Arrow Function

Note: If you're new to TypeScript, check our Getting Started with TypeScript tutorial first.


TypeScript arrow functions are a concise syntax for writing function expressions with support for type annotations.

Here's a short example of arrow functions. You can read the rest of the tutorial to learn more.

Example

// An arrow function to add two numbers
const addNumbers = (a: number, b: number): number => a + b;

// Call the function with two numbers
const result: number = addNumbers(5, 3);
console.log(result);

// Output: 8

In this example, addNumbers() is an arrow function that takes two parameters, a and b, and returns their sum.


Arrow Function Syntax

The syntax of the arrow function is:

let myFunction = (arg1: Type1, arg2: Type2, ...argN: TypeN): ReturnType => {
    statement(s)
}

Here,

  • myFunction - The name of the function.
  • arg1, arg2, ...argN - The function arguments.
  • statement(s) - The function body.
  • ReturnType - The return type of the function (optional).

If the body has a single statement or expression, you can write the arrow function as:

let myFunction = (arg1: Type1): ReturnType => expression;

Notice that we haven't used curly braces {} in this case. That's because the above syntax is a shorthand that doesn't require curly braces or the return statement.


Regular Function vs. Arrow Function

Regular Function vs. Arrow Function

To see the difference between a regular function expression and an arrow function, let's consider a function that multiplies two numbers.

Using a regular function:

// Regular function 
let multiply = function(x: number, y: number): number {
    return x * y;
};

Using an arrow function:

// Arrow function
let multiply = (x: number, y: number): number => x * y;

Here, both the regular function expression and the arrow function perform the multiplication of two numbers.

As you can see, the syntax of the arrow function is more clear and concise.


Implicit Return in Arrow Functions

The shorthand form of the arrow function doesn't require a return statement to return values.

Instead, it implicitly returns the resulting value of the expression in the function body. For example,

// Arrow function that returns the product of two numbers
let multiply = (x: number, y: number): number => x * y;

console.log(multiply(9, 5));

// Output: 45

Use 'return' When Curly Braces Are Present

However, you need to use the return statement if you don't use the shorthand form, i.e., if you use curly braces {} with the arrow function.

Not using the return statement in such cases will result in the arrow function returning undefined. For example,

// Using the return statement
let multiply = (x: number, y: number) => {
    return x * y;
}

// Omitting the return statement
let divide = (x: number, y: number) => {
    x / y;
}

console.log(multiply(9, 5));  // Output: 45
console.log(divide(9, 5));  // Output: undefined

As you can see, the divide() function returned undefined because it's an arrow function that uses curly braces {} but no return statement.

You can fix this by adding a return statement or using the shorthand form:

// Valid: Using the return statement
let divide = (x: number, y: number) => {
    return x / y;
}

// Valid: Using the shorthand form
// No curly braces or the return statement
let divide = (x: number, y: number) => x / y;

Example 1: Arrow Function With No Argument

If a function doesn't take any argument, then you should use empty parentheses. For example,

const sayHello = (): string => "Hello, World!";
// Call the arrow function and print its return value console.log(sayHello()); // Output: Hello, World!

In this example, when sayHello() is called, it executes the arrow function, which returns the string Hello, World!.


Example 2: Arrow Function With One Argument

const square = (x: number): number => x * x;
// Use the arrow function to square a number console.log(square(5)); // Output: 25

The arrow function square() takes one argument x and returns its square.

Hence, calling square() with the value 5 returns 25.


this Keyword With Arrow Function

Inside a regular function, this keyword usually refers to the function where it is called.

However, this is not associated with arrow functions. So, whenever you call this, it refers to its parent scope.

Let's clarify this by comparing how this behaves in a regular function versus how it behaves in an arrow function.

Inside a Regular Function

// Constructor function to create Person object
function Person(this: any) {
    this.name = "Jack";
    this.age = 25;

    this.sayName = function () {

// this is accessible console.log(this.age);
function innerFunc(this: any) {
// this refers to the global object and is not accessible console.log(this.age); console.log(this);
} innerFunc(); } } let x = new (Person as any)(); x.sayName();

Output

25
undefined
<ref *1> Object [global] {...}

Here, this.age inside this.sayName() is accessible because this.sayName() is a method of an object.

However, innerFunc() is a normal function and this.age is not accessible because this refers to the global object.

Hence, this.age inside the innerFunc() function is undefined.

Inside an Arrow Function

// Constructor function
function Person(this: any) {
    
    this.name = 'Jack';
    this.age = 25;
    this.sayName = function () {

        console.log(this.age);

let innerFunc = (): void => { console.log(this.age); }
innerFunc(); } } const x = new (Person as any)(); x.sayName();

Output

25
25

Here, innerFunc() is an arrow function.

And inside the arrow function, this refers to the parent's scope, i.e., the scope of the Person object. Hence, this.age gives 25.


More on Arrow Function

Arrow Function as an Expression

You can use arrow functions dynamically in expressions. For example,

let age: number = 5;

// Use arrow functions as expressions in ternary operator 
// to dynamically assign functionality
let welcome: () => void = (age < 18) ?
    () => console.log("Child") :
    () => console.log("Adult");

welcome(); 


// Output: Child

In this example, an arrow function is created based on the condition of whether age is less than 18 or not.

If age is less than 18, the function will print Child. Otherwise, it will print Adult.

Hence, when the function is called, we get Child as output since age is 5.

Multiline Arrow Functions

If a function body has multiple statements, you need to put them inside curly brackets {}. For example,

let sum = (a: number, b: number): number => { let result = a + b; return result; };
let result1: number = sum(5, 7); console.log(result1); // Output: 12
Things You Should Avoid With Arrow Functions

1. You should not use arrow functions to create methods inside objects.

let person = {
    name: "Jack",
    age: 25,

sayName: () => { console.log(this.age); }
} person.sayName(); // Output: undefined

2. You cannot use an arrow function as a constructor.

let Foo = (): void => {};
let foo = new (Foo as any)();

// Output: TypeError: Foo is not a constructor

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges