How to Specify Return Type in TypeScript Arrow Functions?

Arrow functions provide a syntax for writing functions in JavaScript and TypeScript, making your code cleaner and more readable. Specifying return types in TypeScript ensures type safety and helps catch errors early during development. In this tutorial, I will explain how to specify the return type in TypeScript arrow functions.

What Are Arrow Functions in TypeScript?

Arrow functions are a shorthand form of function expressions in JavaScript and TypeScript. They are particularly useful for maintaining the this context within methods and for writing more concise code. Here’s a basic example of an arrow function:

const add = (a: number, b: number): number => {
    return a + b;
};

In the example above, (a: number, b: number) denotes the parameter types, and : number specifies the return type. This ensures that the function add always returns a number.

Check out How to Use Generic Arrow Functions in TypeScript?

Specify Return Types in TypeScript Arrow Functions

It is easy to specify the return types in TypeScript arrow functions. You place the return type after the parameter list and before the arrow (=>). This practice is essential for maintaining type safety and making your code more predictable.

Example: Calculate Sales Tax

Let’s consider a more practical example involving a function to calculate sales tax in the USA:

const calculateSalesTax = (amount: number, taxRate: number): number => {
    return amount * (taxRate / 100);
};

// Example usage
const amount = 100;
const taxRate = 8.5;

const salesTax = calculateSalesTax(amount, taxRate);
console.log(`Amount: $${amount}`);
console.log(`Tax Rate: ${taxRate}%`);
console.log(`Sales Tax: $${salesTax}`);

In this function, calculateSalesTax, we specify that it takes two parameters, amount and taxRate, both of type number. The return type is also number.

Here is the exact output in the screenshot below:

Specify Return Types in TypeScript Arrow Functions

Read How to Pass a Function as a Parameter in TypeScript?

Example: Fetch User Data

Here’s another example where we fetch user data and ensure the function returns a specific type:

interface User {
    id: number;
    name: string;
    email: string;
}

const fetchUserData = (userId: number): User => {
    // Simulating fetching user data
    return {
        id: userId,
        name: "John Doe",
        email: "john.doe@example.com"
    };
};

// Example usage
const userId = 123;

const userData = fetchUserData(userId);
console.log("User ID:", userData.id);
console.log("Name:", userData.name);
console.log("Email:", userData.email);

In this example, we define an interface User to describe the structure of the user object. The fetchUserData function takes a userId of type number and returns an object of type User.

I executed the above Typescript code using VS code, and you can see the exact output in the screenshot below:

TypeScript Arrow Functions Specify Return Types

Read How to Use Default Function Parameters in TypeScript?

Using Generics with TypeScript Arrow Functions

Generics allow you to create reusable components that work with any data type. Here’s how you can use generics with arrow functions:

const identity = <T>(value: T): T => {
    return value;
};

const numberIdentity = identity<number>(42); // returns 42
const stringIdentity = identity<string>("Hello, USA!"); // returns "Hello, USA!"

In this example, the identity function takes a parameter of any type T and returns a value of the same type T. This makes the function flexible and reusable for different data types.

Conclusion

In this tutorial, I explained how to specify return types in TypeScript arrow functions with examples.

You may also like: