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.
TypeScript is expanded here with a practical explanation, multiple examples, and beginner-focused checks so the idea is easier to learn from this page alone.
Read the concept first, then trace the example line by line. The important habit is to connect the rule to visible behavior instead of memorizing only the name.
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.
TypeScript becomes much easier when you separate the concept from the tool syntax. First identify the problem being solved, then identify the data or resource being changed, and finally identify the proof that the change worked.
In TypeScript, this topic should be studied through compile-time contracts, generic constraints, object shape, narrowing, and runtime validation. Those points explain not only how to use the feature, but also why it fails when the wrong assumption is made.
The previous audit note was: under 650 content words . This expanded section adds a fuller explanation, concrete examples, and practice guidance so the page can stand on its own for beginners.
A good way to learn this page is to read the normal path once, run or trace the example, then intentionally change one input to observe the different result. That one change teaches more than memorizing several definitions.
Start with a tiny project scenario. For example, imagine one user action, one request, one resource, one function call, or one batch of data. Keep the scenario small enough that every step can be explained without skipping details.
Next, describe the movement of information. Where does the input start? Which rule or component handles it? What result should appear? If the result is wrong, where would you inspect first?
Finally, compare two outcomes. The correct outcome proves that you understand the main rule. The incorrect outcome teaches the symptom, which is what you will recognize later during debugging or interviews.
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);
}
}
type TypescriptState = {
id: string;
title: string;
ready: boolean;
};
function markTypescriptReady(state: TypescriptState): TypescriptState {
return { ...state, ready: true };
}
console.log(markTypescriptReady({ id: '1', title: 'TypeScript', ready: false }));
function requireNonEmptyTypescript(value: string): string {
if (value.trim() === '') {
throw new Error('TypeScript requires a non-empty value');
}
return value;
}
const checked = requireNonEmptyTypescript('demo');
console.log(checked);
Use `<T>` everywhere because it looks advanced.
Use generics only when the caller supplies or influences the type.
Return `any` from API helpers.
Return `Promise<ApiResponse<T>>` or another generic wrapper.
Learning TypeScript only as a term.
Learn it through a working example, a boundary case, and a failure case.
Skipping verification.
Always check output, state, logs, metrics, query results, or compiler feedback.
Changing many things at once while debugging.
Change one setting, input, or line, then inspect the result.
`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.
Start with one tiny example, trace every step, then compare it with a broken version.
Verify the visible result: output, state, log entry, metric, query result, compiler feedback, or rendered behavior.
It often combines vocabulary with behavior. The confusion drops when you trace the input, rule, result, and failure path.
Explore 500+ free tutorials across 20+ languages and frameworks.