Tutorials Logic, IN info@tutorialslogic.com

TypeScript Generics: Reusable Type-Safe Functions and Components

Generic Functions

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.

  • Use generics when the function should work with many types but preserve the exact type.
  • Avoid `any` when the input and output types are related.
  • Let TypeScript infer generic types unless explicit type arguments improve clarity.

Identity and Array Helpers

Identity and Array Helpers
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

Generic Constraints

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.

  • Use `T extends SomeShape` when a generic must contain certain properties.
  • Use `keyof T` when a parameter must be one of an object type’s keys.
  • Return values can stay strongly typed even after generic constraints are applied.

Generic Constraint With keyof

Generic Constraint With keyof
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

Generic Interfaces and API Responses

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.

  • Create generic wrappers for repeated response shapes.
  • Use specific model types for each endpoint’s data.
  • Avoid losing type information by returning `Promise<any>` from API helpers.

Typed API Response

Typed API Response
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);
  }
}
Before you move on

TypeScript Generics: Reusable Type-Safe Functions and Components Mastery Check

5 checks
  • 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.
  • 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.
  • Generics are especially useful for API response wrappers.

TypeScript Generics Questions Learners Ask

`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.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.