What are Generics in TypeScript ? (original) (raw)

Last Updated : 15 Sep, 2025

Generics in TypeScript allow developers to create reusable components that can work with multiple data types while maintaining type safety. Generics are widely used in functions, classes, and interfaces for building reusable and adaptable code.

**Syntax:

function function_name(
parameter_name: data_type_parameter
): return_type_parameter {
// Rest of the code
}

**In the above syntax:

**Example 1: Generic Function with Parameters

Generic functions in TypeScript allow you to define functions that can work with multiple data types while maintaining type safety.

JavaScript `

function displayData (parameter :type_parameter) : type_parameter{ return parameter; }

let result1 = displayData ("GeeksforGeeks"); let result2 = displayData ("Hello World !!"); let result3 = displayData (1234567890);

console.log(result1); console.log(result2); console.log(result3);

`

**Output:

GeeksforGeeks
Hello World !!
1234567890

**In this example:

**Example 2: Generic Function with Array Return Type

A generic function can also work with arrays, ensuring type safety while handling collections of data.

JavaScript `

let displayResult = (data_item : type_parameter[]) : type_parameter[] => { return new Array ().concat(data_item); }

let numbersArray = displayResult ([50 , 60 , 80 , 90]);

let stringArray = displayResult (["Hello World", "GeeksforGeeks"]);

console.log(numbersArray); console.log(stringArray);

numbersArray.push(100); stringArray.push("Apple");

console.log(numbersArray); console.log(stringArray);

`

**Output:

[ 50, 60, 80, 90 ]
[ 'Hello World', 'GeeksforGeeks' ]
[ 50, 60, 80, 90, 100 ]
[ 'Hello World', 'GeeksforGeeks', 'Apple' ]

**In this example:

**Example 3: Multiple Generic Type Parameters

Functions can also take multiple generic type parameters, allowing flexible handling of different types together.

JavaScript `

let displayResult = <type_1, type_2> (id : type_1, name : type_2) => { return id + " - " + name; }

let data_1 = displayResult<number, string>(2000, "GeeksforGeeks");

let data_2 = displayResult<number, string>(2001, "Hello World !!");

console.log(data_1); console.log(data_2);

`

**Output:

2000 - GeeksforGeeks
2001 - Hello World !!

**In this example:

**Example 4: Generics with Constraints

Generic constraints ensure that only values meeting certain requirements can be passed to a generic function.

JavaScript `

function getLength<T extends { length: number }>(arg: T): number { return arg.length; }

console.log(getLength("Hello")); console.log(getLength([10, 20, 30]));

`

Output:

5
3

**In this example: