TypeScript generics let you write reusable code that keeps the specific type of the value passed in. Instead of using `any`, a generic type parameter preserves information so TypeScript can check inputs and outputs accurately.
Generics are used in arrays, promises, API responses, repositories, React components, utility functions, maps, form helpers, and many library types. They are one of the most important TypeScript features for building reusable but safe abstractions.
A generic function declares a type parameter, commonly named `T`. TypeScript infers `T` from the argument when the function is called, then uses that same type in the return value or other parameters.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const firstName = first(["Asha", "Ravi"]);
const firstScore = first([88, 92, 75]);
// firstName is string | undefined
// firstScore is number | undefined
Sometimes a function can work with many types, but each type must have a required property or shape. Constraints use `extends` to tell TypeScript what operations are safe inside the function.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = {
id: 101,
name: "Asha",
active: true,
};
const name = getProperty(user, "name"); // string
const active = getProperty(user, "active"); // boolean
// getProperty(user, "email");
// Error: "email" is not a key of user
Generics are especially useful for API response wrappers. The response shape may always include status and error fields, while the `data` field changes depending on the endpoint.
type ApiResponse<T> = {
success: boolean;
data: T;
error?: string;
};
type Course = {
id: number;
title: string;
lessons: number;
};
async function parseResponse<T>(response: Response): Promise<ApiResponse<T>> {
return response.json() as Promise<ApiResponse<T>>;
}
async function loadCourse(id: number) {
const response = await fetch(`/api/courses/${id}`);
const result = await parseResponse<Course>(response);
if (result.success) {
console.log(result.data.title);
}
}
`T` is a type parameter. It acts like a variable for a type and is filled in when the generic function, class, or type is used.
No. `any` discards type safety. Generics preserve and reuse type information.
A plain string says any property name is allowed, even one that does not exist on the object. extends keyof T limits the key to the actual property names of the generic object type. In a helper such as getValue<T, K extends keyof T>(obj, key), TypeScript can prove that obj[key] is safe and that the return type matches the selected property.
Practice, interview questions, and compiler links for TypeScript Generics.
Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.
Explore 500+ free tutorials across 20+ languages and frameworks.
Fresh tutorials, interview guides, and coding practice in your inbox.