How to Strongly Type the Return Value of any Function in TypeScript ?
Last Updated :
13 Feb, 2024
In TypeScript, specifying the return type after a function’s parameters with a colon ensures a consistent return value type. This enhances code reliability by enforcing expected return types. It is a fundamental feature of TypeScript that ensures functions consistently produce values of the specified type. The below methods can be used to achieve this task:
Directly specifying the return type
You can specify the type of the return value of a function directly by using the colon(:) syntax followed by the return type.
Syntax:
function functionName(): returnType{}
Example: The below code will show how you can directly type the return value of a function.
Javascript
function sum(a: number, b: number): number {
return a + b;
}
const result: number = sum(15, 30);
console.log(result);
|
Output:
45
Using Generic type
The generic type can be used to declare the functions with a specified return as well as accepting values. It will return the value of the same type which it takes.
Syntax:
function functionName<T>(): T{}
Example: The below code will explain the use of generic type to type return value of a function.
Javascript
function genericInput<T>(input: T): T {
return input;
}
let noResult: number =
genericInput<number>(10);
let strResult: string =
genericInput<string>( "Geek" );
console.log( "Number result:" , noResult);
console.log( "String result:" , strResult);
|
Output:
Number result: 10
String result: Geek
Using TypeScript Interfaces
You can also use TypeScript interface to create a blue print of the return type value of a function which can be later used to assign the return type to the function.
Syntax:
interface interfaceName{}
Example: The below code practically implements the interface to type the return value of the function.
Javascript
interface ReturnValue {
result: number;
}
function myFunc(): ReturnValue {
return { result: 10 };
}
const result: ReturnValue = myFunc();
console.log( "Result:" , result.result);
|
Output:
Result: 10
Share your thoughts in the comments
Please Login to comment...