How to use TypeScript Interfaces In Typescript

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

How to Strongly Type the Return Value of any Function 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:

Table of Content

  • Directly specifying the return type
  • Using Generic type
  • Using TypeScript Interfaces

Similar Reads

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....

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....

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....

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....