TypeScript Working with Generic Type Variables
Last Updated :
24 Apr, 2025
In TypeScript, working with generic type variables is a powerful feature that allows you to create functions and classes that can work with a variety of data types while maintaining type safety.
Note: When you declare a generic function or class, you introduce a type variable enclosed in angle brackets (<>). This type variable serves as a placeholder for a specific type that will be provided when the function or class is used. This enables you to create more flexible and reusable code.
Syntax:
function identity<Type>(arg: Type): Type {
// Body of function
}
Parameters:
- Type is the type of datatype.
Example 1: In this example, we have created an identity function that is a generic function. we will first pass a string to this and then pass a number to this. Our function is able to infer the type of variable and print it. We are also printing its type using the 'typeof()' function.
JavaScript
function identity<Type>(arg: Type): Type {
return arg;
}
// The result is of type string
let result = identity("GeeksforGeeks");
// The result2 is of type number
let result2 = identity(42);
console.log(result + " " + typeof result);
console.log(result2 + " " + typeof result2);