Open In App

How to Strongly Type the Return Value of any Function in TypeScript ?

Last Updated : 08 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

Using Type Alias

Type aliasing in TypeScript allows developers to create custom named types, including those for function return values. This approach provides clarity and reusability when specifying the return type of functions.

Example:

JavaScript
type Result = {
    value: number;
};

function generateResult(): Result {
    return { value: 22 };
}

const result: Result = generateResult();
console.log(result.value); // Output: 22

Output:

22


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads