TypeScript Generics
Learn how to create reusable, type-safe functions, interfaces and classes that work with different data types using Generics.
T.
1. What are Generics?
Generics are a TypeScript feature that allows types to be passed as parameters when defining functions, interfaces, classes and other type structures.
A generic type parameter acts like a placeholder for a type. The actual type can be supplied explicitly or inferred by TypeScript from the arguments.
Basic Syntax
function identity<T>(value: T): T {
return value;
}
const numberValue = identity<number>(100);
const stringValue = identity<string>("TypeScript");
console.log(numberValue);
console.log(stringValue);
Expected Output
100
TypeScript
Here, T represents the type of the value.
When the function is called with a number, T is number.
When called with a string, T is string.
2. Generics Workflow Diagram
Understand how a generic function accepts a type and uses it to preserve type information from input to output.
Define Generic
Declare a type parameter such as T.
Pass Value
Provide a value whose type can be inferred or specified.
Use Type T
The function operates using the selected type.
Return Value
The return type preserves the relationship with the input.
3. Why Do We Need Generics?
Without Generics, developers may create separate functions for different data types even when the logic is identical.
Without Generics
function getNumber(value: number): number {
return value;
}
function getString(value: string): string {
return value;
}
console.log(getNumber(100));
console.log(getString("Hello"));
With Generics
function getValue<T>(value: T): T {
return value;
}
console.log(getValue(100));
console.log(getValue("Hello"));
Expected Output
100
Hello
4. Generic Functions
A generic function declares a type parameter after its name. That parameter can be reused in the function's arguments and return type.
Example
function identity<T>(value: T): T {
return value;
}
const studentName = identity<string>("Rahul");
const studentAge = identity<number>(22);
const isEnrolled = identity<boolean>(true);
console.log(studentName);
console.log(studentAge);
console.log(isEnrolled);
Expected Output
Rahul
22
true
How It Works
String
T becomes string when the input is "Rahul".
Number
T becomes number when the input is 22.
Boolean
T becomes boolean when the input is true.
5. Generic Type Inference
TypeScript can often infer a generic type parameter from the arguments. This means that explicitly writing the type parameter is not always necessary.
Example
function identity<T>(value: T): T {
return value;
}
const numberValue = identity(500);
const textValue = identity("Welcome");
console.log(numberValue);
console.log(textValue);
Expected Output
500
Welcome
TypeScript infers T as number for the first call and string for the second call. The inferred return types are also number and string respectively.
6. Generics with Arrays
Generics can be used to define functions that work with arrays of different element types. For example, one function can retrieve the first item from either a string array or a number array.
Example
function getFirstItem<T>(items: T[]): T | undefined {
return items[0];
}
const firstNumber = getFirstItem([10, 20, 30]);
const firstName = getFirstItem(["Rahul", "Priya", "Amit"]);
console.log(firstNumber);
console.log(firstName);
Expected Output
10
Rahul
The function accepts an array of T and returns either an item of type T or undefined when the array is empty. TypeScript infers T from the array.
7. Generics with Multiple Type Parameters
A generic function can have more than one type parameter. Each parameter can represent a different type.
Example
function createPair<T, U>(first: T, second: U): [T, U] {
return [first, second];
}
const studentRecord = createPair("Rahul", 22);
const productRecord = createPair(101, "Keyboard");
console.log(studentRecord);
console.log(productRecord);
Expected Output
[ 'Rahul', 22 ]
[ 101, 'Keyboard' ]
T represents the first value's type and U represents the second value's type. The tuple return type preserves both types and their order.
8. Generic Interfaces
An interface can accept a type parameter so its structure can be reused with different types of data.
Example: API Response
interface ApiResponse<T> {
success: boolean;
message: string;
data: T;
}
interface Student {
id: number;
name: string;
}
const response: ApiResponse<Student> = {
success: true,
message: "Student loaded successfully",
data: {
id: 101,
name: "Rahul"
}
};
console.log(response.success);
console.log(response.message);
console.log(response.data.name);
Expected Output
true
Student loaded successfully
Rahul
Generic Interface Workflow
ApiResponse<T>
Defines a reusable response structure.
Student Type
T is specified as Student.
Response Object
data contains a Student object.
9. Generic Classes
A generic class accepts a type parameter that can be used by its properties and methods. This helps the same class work with different kinds of stored data.
Example: Data Container
class Box<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
const numberBox = new Box<number>(100);
const stringBox = new Box<string>("TypeScript");
console.log(numberBox.getValue());
console.log(stringBox.getValue());
Expected Output
100
TypeScript
Generic Class Diagram
Box<T>
One class definition for different value types.
Box<number>
Stores a numeric value such as 100.
Box<string>
Stores a string value such as TypeScript.
10. Introduction to Generic Constraints
Sometimes a generic function needs to access a particular property or use a specific capability of its input. In that case, we can constrain the generic type parameter.
Example Preview
function getLength<T extends { length: number }>(value: T): number {
return value.length;
}
console.log(getLength("TypeScript"));
console.log(getLength([10, 20, 30]));
Expected Output
10
3
The constraint requires T to have a numeric length property. Generic Constraints will be explained in detail on the next page.
11. Advantages of Generics
Code Reusability
Write one reusable function or class for multiple types.
Type Safety
Maintain the relationship between inputs, stored values and outputs.
Less Duplicate Code
Avoid writing separate implementations for similar operations.
Better Maintainability
Keep reusable code consistent as an application grows.
Summary
Generics allow functions, interfaces and classes to work with multiple types while preserving type information. Type parameters such as T can be inferred or specified explicitly. Multiple type parameters can represent different values, and generic classes can store typed data.
Next, learn Generic Constraints and how to restrict generic types to values that provide specific properties or capabilities.