How to use Generic type In Typescript
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.
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
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