How to Specify Return Type in TypeScript Arrow Functions ?
Last Updated :
10 Jan, 2024
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:
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
.
Javascript
const add = (a: number, b: number): number => {
return a + b;
};
console.log(add(3, 4));
|
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.
Javascript
const multiply = (a: number, b: number) => a * b;
console.log(multiply(5, 6));
|
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.
Javascript
const divide: (a: number, b: number) =>
number = (a, b) => {
return a / b;
};
console.log(divide(10, 2));
|
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.
Javascript
interface MathOperation {
(a: number, b: number): number;
}
const subtract: MathOperation = (a, b) => a - b;
console.log(subtract(8, 3));
|
Output:
5
Share your thoughts in the comments
Please Login to comment...