Open In App

TypeScript Generic Types

Last Updated : 07 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript Generic Types can be used by programmers when they need to create reusable components because they are used to create components that work with various data types and this provides type safety. The reusable components can be classes, functions, and interfaces. TypeScript generics can be used in several ways like function, class, and interface generics.

Syntax:

function functionName<T> (returnValue : T) : T {
return returnValue;
}

Example 1: In this example, we have created a generic function that can accept any type of data, we need to pass the value in the parameter by giving them any kind of data type and then we can reverse that value by the use of the reverseArray function.

Javascript




function reverseArray<T>(array: T[]): T[] {
    return array.reverse();
}
 
const strArray: string[] = reverseArray(["Java", "Python", "C++"]);
const numArray: number[] = reverseArray([1, 2, 3, 4, 5]);
const boolArray: boolean[] = reverseArray([false, true]);
 
console.log(strArray);
console.log(numArray);
console.log(boolArray);


Output:

[ 'C++', 'Python', 'Java' ]
[ 5, 4, 3, 2, 1 ]
[ true, false ]

Example 2: In this example, we have created a generic interface by using that we are creating object and string type of value and printing them in the console.

Javascript




interface Resource<T> {
    id: number;
    resourceName: string;
    data: T;
}
const person: Resource<object> = {
 
    // Generic interface with objects
    id: 1,
    resourceName: 'Person',
    data: {
        name: 'John',
        age: 25,
    }
}
console.log(person);
const employee: Resource<string[]> =
{
    // Generic interface with strings array
    id: 2,
    resourceName: 'Employee',
    data: ['Employee 1', 'Employee 1']
}
console.log(employee);


Output:

 {
"id": 1,
"resourceName": "Person",
"data": {
"name": "John",
"age": 25
}
}
{
"id": 2,
"resourceName": "Employee",
"data": [
"Employee 1",
"Employee 1"
]
}


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads