How to Specify Return Type in TypeScript Arrow Functions ?
To Specify the return type in the TypeScript arrow function, we have multiple approaches. In this article, we are going to learn how to Specify the type in the TypeScript arrow function.
Below are the approaches used to Specify the return type in the TypeScript arrow function:
Table of Content
- Explicit Return Type Annotation
- Type Inference
- Function Declaration
- Interface with Function Signature
- Using Type Alias for Function Signature
Explicit Return Type Annotation
You explicitly annotate the return type after the parameter list using ‘:’
Example: Here, the add
the function takes two parameters of type number
and returns a value of type number
.
const add = (a: number, b: number): number => {
return a + b;
};
console.log(add(3, 4)); // Output: 7
Output:
7
Type Inference
TypeScript infers the return type based on the return statement when the function body is a single expression.
Example: In this case, TypeScript infers that the return type is number
based on the multiplication operation.
const multiply = (a: number, b: number) => a * b;
console.log(multiply(5, 6)); // Output: 30
Output:
30
Function Declaration
You can specify the return type when declaring the function separately.
Example: You explicitly declare the function type before the assignment, specifying the return type.
const divide: (a: number, b: number) =>
number = (a, b) => {
return a / b;
};
console.log(divide(10, 2)); // Output: 5
Output:
5
Interface with Function Signature
An interface defines a function signature, and you use it to declare the arrow function.
Example: An interface defines a function signature, and you use it to declare the arrow function.
interface MathOperation {
(a: number, b: number): number;
}
const subtract: MathOperation = (a, b) => a - b;
console.log(subtract(8, 3)); // Output: 5
Output:
5
Using Type Alias for Function Signature
Type aliases in TypeScript provide a way to give a name to a type. You can use type aliases to define the signature of the function and then use it to specify the return type of the arrow function.
Example: In this example we defines a type alias MathOperation for a function taking two numbers and returning a number. It’s assigned to a function power, calculating the exponentiation of 2 to 3.
type MathOperation = (a: number, b: number) => number;
const power: MathOperation = (base, exponent) => Math.pow(base, exponent);
console.log(power(2, 3));
Output:
8
Contact Us