Generics allow you to create reusable components, functions, classes, and interfaces that work over a variety of types while maintaining full type safety.
flowchart LR
A["Generic Function: identity<T>(arg: T): T"] --> B["Call: identity<string>('hello') -> returns string"]
A --> C["Call: identity<number>(100) -> returns number"]
// Generic Function
function wrapInArray<T>(value: T): T[] {
return [value];
}
const stringArray = wrapInArray("TypeScript"); // Inferred type: string[]
const numberArray = wrapInArray(42); // Inferred type: number[]
// Generic Interface for API Responses
interface ApiResponse<TData> {
status: number;
message: string;
payload: TData;
timestamp: string;
}
interface UserData {
id: number;
name: string;
}
const userResponse: ApiResponse<UserData> = {
status: 200,
message: "Success",
payload: { id: 1, name: "Alice" },
timestamp: new Date().toISOString()
};
// Generic Class with Constraints
class DataStorage<T extends { id: string | number }> {
private data: Map<string | number, T> = new Map();
public addItem(item: T): void {
this.data.set(item.id, item);
}
public getItem(id: string | number): T | undefined {
return this.data.get(id);
}
}
const storage = new DataStorage<{ id: string; name: string }>();
storage.addItem({ id: "item_1", name: "Laptop" });
console.log(storage.getItem("item_1")?.name);
T, U, V for simple cases, or descriptive names like TData, TError, TRequest for complex APIs.extends: Restrict generic type parameters (<T extends Lengthwise>) to ensure required properties exist.Write a generic function getFirstElement<T>(arr: T[]): T | undefined that returns the first item of any typed array.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With