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