How Do Generics Work in TypeScript?

Learn How Do Generics Work in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Generics in TypeScript

Generics are one of the most powerful features of TypeScript. They allow developers to create reusable functions, interfaces, classes, and type definitions that work with different data types while preserving type safety. Instead of writing separate implementations for strings, numbers, and objects, you can write one implementation that adapts to the types supplied when it is used.

Without generics, developers sometimes use the any type to make a function accept different kinds of values. Although this approach provides flexibility, it removes many of TypeScript's useful checks. Generics provide an alternative by allowing a function to accept different types without losing information about its inputs and outputs.

Generics are widely used in reusable utilities, API response models, collections, repositories, React components, data transformation functions, and libraries. Understanding them helps you build flexible APIs that remain strongly typed as an application grows.

1. Why Do We Need Generics?

Consider a function that returns the value passed to it. If you create separate functions for strings and numbers, you repeat the same logic even though the behavior is identical.

function getString(value: string): string {
  return value;
}

function getNumber(value: number): number {
  return value;
}

console.log(getString("TypeScript"));
console.log(getNumber(100));

Both functions simply return their inputs. Their implementations differ only because their parameter and return types are different.

A generic function can express the same behavior once:

function identity<T>(value: T): T {
  return value;
}

console.log(identity("TypeScript"));
console.log(identity(100));
console.log(identity(true));

The generic parameter T represents a type that is determined when the function is called. When a string is supplied, T is inferred as string. When a number is supplied, T is inferred as number.

The most important detail is that the return type remains connected to the input type. A string input produces a string result, while a numeric input produces a numeric result. The function stays reusable without falling back to any.

2. Understanding Generic Type Parameters

A generic type parameter is a placeholder for a type. It allows a function or type definition to describe relationships between values before the exact types are known.

Generic type parameters are commonly named T, U, K, and V, although descriptive names can improve readability in complex declarations.

function getValue<T>(value: T): T {
  return value;
}

const courseName = getValue("TypeScript");
// Inferred return type: string

const courseId = getValue(101);
// Inferred return type: number

const isPublished = getValue(true);
// Inferred return type: boolean

console.log(courseName);
console.log(courseId);
console.log(isPublished);

The letter T has no special meaning to the compiler. It is a conventional name for a type parameter. You could use another valid identifier, such as TValue, to make the purpose more descriptive.

TypeScript generally infers the type argument from the supplied value, so you usually do not need to specify it manually. Generic parameters become especially valuable when multiple inputs and outputs must remain related to the same type.

3. Explicitly Supplying Generic Type Arguments

TypeScript often infers generic type arguments automatically, but you can provide them explicitly when you want to specify the intended type or when inference needs additional information.

function identity<T>(value: T): T {
  return value;
}

const courseName = identity<string>("TypeScript");
const courseId = identity<number>(101);

console.log(courseName);
console.log(courseId);

In the first call, T is explicitly supplied as string. In the second call, T is supplied as number. TypeScript checks the argument against the chosen type parameter.

Explicit type arguments are useful when inference cannot determine the desired type precisely or when a generic function produces a result whose type cannot be inferred entirely from its inputs. However, allowing inference to handle straightforward calls usually keeps code shorter and easier to read.

4. Generic Functions with Arrays

Generics are particularly useful when creating reusable functions that operate on arrays. A generic function can process arrays of different element types while preserving the element type in its result.

function getFirstItem<T>(
  items: T[]
): T | undefined {
  return items[0];
}

const firstNumber = getFirstItem([10, 20, 30]);
const firstCourse = getFirstItem([
  "HTML",
  "CSS",
  "TypeScript"
]);

console.log(firstNumber);
console.log(firstCourse);

When the function receives an array of numbers, T is inferred as number. When it receives an array of strings, T is inferred as string.

The return type is T | undefined because the supplied array may be empty. This makes the function more accurate than one that assumes the first element always exists.

The same technique can be used for selecting array elements, transforming data, retrieving collection values, and writing reusable utilities for objects or other domain models.

5. Using Multiple Generic Type Parameters

A generic function can declare multiple type parameters when it needs to preserve relationships between different input values or between inputs and outputs.

function createPair<T, U>(
  first: T,
  second: U
): [T, U] {
  return [first, second];
}

const coursePair = createPair("TypeScript", 101);
const userPair = createPair(25, true);

console.log(coursePair);
console.log(userPair);

The first type parameter T describes the first argument, while U describes the second. The returned tuple preserves both types and their positions.

In the first call, the result is typed as a tuple containing a string and a number. In the second call, it is a tuple containing a number and a Boolean.

Multiple type parameters are useful for key-value pairs, mapping functions, API request and response wrappers, comparisons, and utilities that combine different data models. Use them when each type parameter represents a meaningful distinction.

6. Generic Type Constraints

A generic type parameter can represent many possible types. Sometimes, however, a function needs a value to provide a particular property or capability. Generic constraints allow you to restrict the types that may be supplied.

The extends keyword is commonly used to define a constraint. It means that a type argument must satisfy the specified type rather than being completely unrestricted.

interface HasLength {
  length: number;
}

function getLength<T extends HasLength>(
  value: T
): number {
  return value.length;
}

console.log(getLength("TypeScript"));
console.log(getLength([10, 20, 30]));
console.log(getLength({ length: 5 }));

// Compile-time error:
// getLength(100);

The HasLength interface describes a value containing a numeric length property. The generic constraint permits strings, arrays, and compatible objects because they provide that property.

A number does not satisfy this constraint, so TypeScript rejects that argument. The constraint gives the function permission to access length without requiring any or an unsafe type assertion.

Constraints should describe the capabilities a function actually requires. They help preserve flexibility while guaranteeing the properties or methods needed by the implementation.

7. Generic Constraints with keyof

TypeScript's keyof operator produces a type representing the property keys of another type. Combined with generics, it allows a function to accept only keys that exist on a specified object type.

function getProperty<
  T,
  K extends keyof T
>(
  object: T,
  key: K
): T[K] {
  return object[key];
}

const course = {
  id: 101,
  title: "TypeScript Fundamentals",
  published: true
};

const courseTitle = getProperty(course, "title");
const courseId = getProperty(course, "id");

console.log(courseTitle);
console.log(courseId);

// Compile-time error:
// getProperty(course, "price");

The generic parameter K is constrained to keys of T. If T represents the course object, valid keys include id, title, and published.

The indexed access type T[K] represents the type of the selected property. As a result, accessing title returns a string, while accessing id returns a number.

This pattern is useful for property access utilities, mapping data, reusable form helpers, sorting functions, and APIs that need to select properties without losing their original types.

8. Generic Interfaces

Interfaces can also declare generic type parameters. This allows the same interface structure to describe objects containing different kinds of data.

interface ApiResponse<T> {
  success: boolean;
  data: T;
  message: string;
}

const courseResponse: ApiResponse<string[]> = {
  success: true,
  data: ["HTML", "CSS", "TypeScript"],
  message: "Courses loaded"
};

const countResponse: ApiResponse<number> = {
  success: true,
  data: 12,
  message: "Course count loaded"
};

console.log(courseResponse.data);
console.log(countResponse.data);

ApiResponse<T> defines a reusable response structure with a generic data property. One response can contain an array of strings, while another can contain a number.

Generic interfaces are useful for API responses, repository results, pagination models, state containers, and data-processing abstractions. They allow a shared structure to retain accurate type information instead of representing every result as any.

A generic interface describes a compile-time contract. If an API returns JSON, validate the actual response at runtime before trusting that it conforms to the declared structure.

9. Generic Classes

Classes can use generic type parameters to store and manipulate values of different types while maintaining type safety. The generic parameter becomes part of the instance's type and is used by its members.

class Box<T> {
  constructor(public value: T) {}

  getValue(): T {
    return this.value;
  }

  setValue(value: T): void {
    this.value = value;
  }
}

const numberBox = new Box(100);
const courseBox = new Box("TypeScript");

numberBox.setValue(200);
courseBox.setValue("Advanced TypeScript");

console.log(numberBox.getValue());
console.log(courseBox.getValue());

TypeScript infers T as number for numberBox and string for courseBox. Each instance retains its own generic type, so a value of an incompatible type cannot be passed to setValue() through normally checked code.

Generic classes are useful for reusable containers, caches, repositories, data stores, and components that manage different types of values. Use them when a shared class behavior genuinely needs to preserve a relationship with the stored data type.

10. Default Generic Type Parameters

Generic type parameters can define default types. A default is used when a type argument is not supplied and cannot be inferred from the relevant context.

interface ApiResult<T = string> {
  data: T;
  success: boolean;
}

const messageResult: ApiResult = {
  data: "Operation completed",
  success: true
};

const countResult: ApiResult<number> = {
  data: 12,
  success: true
};

console.log(messageResult.data);
console.log(countResult.data);

ApiResult uses string as its default type argument. The first variable therefore uses the default, while the second explicitly supplies number.

Default type parameters are useful when one type is common and most users should not have to specify it manually. They should still reflect meaningful defaults for the abstraction rather than being chosen only to make a type declaration shorter.

11. Generic Functions with Multiple Constraints

Generic functions can use constraints to express required relationships between input types. For example, a reusable utility may need to work with object values while selecting a property whose key is valid for the input object.

function compareProperty<
  T extends object,
  K extends keyof T
>(
  first: T,
  second: T,
  key: K
): boolean {
  return first[key] === second[key];
}

const firstUser = {
  id: 1,
  name: "Asha"
};

const secondUser = {
  id: 2,
  name: "Asha"
};

console.log(compareProperty(firstUser, secondUser, "name"));
console.log(compareProperty(firstUser, secondUser, "id"));

The first constraint requires T to be an object type. The second restricts K to property keys of that object. The function can then access the selected property on both objects while preserving type information.

Constraints are particularly useful for reusable sorting, filtering, comparison, and mapping utilities. They let developers define exactly which capabilities a generic type must support without limiting the function to one concrete interface.

12. Generics with Asynchronous Functions

Generic parameters can describe values returned from asynchronous operations. They are particularly useful for reusable service methods, API wrappers, and functions that process different types of data through a shared asynchronous workflow.

async function executeTask<T>(
  task: () => Promise<T>
): Promise<T> {
  return await task();
}

async function loadCourseName(): Promise<string> {
  return "TypeScript Fundamentals";
}

async function loadCourseCount(): Promise<number> {
  return 12;
}

async function main(): Promise<void> {
  const courseName = await executeTask(loadCourseName);
  const courseCount = await executeTask(loadCourseCount);

  console.log(courseName);
  console.log(courseCount);
}

void main();

The generic parameter T represents the value returned by the supplied asynchronous function. The wrapper preserves the result type instead of forcing every operation to return the same concrete type.

The generic type describes the successful resolved value, but the Promise may still reject. Callers should use appropriate error handling when the operation depends on network requests, external resources, or other asynchronous work that can fail.

13. Generics vs any

Generics and any may both allow functions to work with different input types, but they preserve different amounts of type information. Any removes most checking for a value, while generics retain relationships between inputs, outputs, and other related values.

Feature any Generics
Works with different types Yes Yes
Preserves input-output type relationships Generally no Yes, when modelled by the generic signature
Provides meaningful type checking Greatly reduced Yes
Supports reusable contracts With limited type guarantees With preserved type information
function identityAny(value: any): any {
  return value;
}

function identityGeneric<T>(value: T): T {
  return value;
}

const anyResult = identityAny("TypeScript");
const stringResult = identityGeneric("TypeScript");

console.log(anyResult);
console.log(stringResult);

// TypeScript preserves string for stringResult.
// anyResult has type any, so many checks are bypassed.

The generic function preserves the string type when the input is a string. The any-based version loses that useful relationship because the declared return type is any.

Prefer generics when the same logic should support several types while retaining type safety. Use any only when bypassing static checking is a deliberate decision, such as during a controlled migration or around an unavoidable untyped boundary.

14. Common Mistakes When Using Generics

Using generics without a real type relationship

A generic parameter is useful when a type varies or when relationships between types must be preserved. If a function only supports one concrete type, a simple non-generic signature may be clearer.

Using any instead of a generic

Any removes many compiler checks. Use generics to preserve the connection between inputs and outputs when the function should support different types safely.

Accessing properties without constraints

An unrestricted generic type does not guarantee that a property exists. Add an appropriate constraint or use keyof when the function needs to access a known property.

Adding too many type parameters

Excessive generic parameters can make a function difficult to understand. Add a parameter only when it represents a meaningful type or relationship.

Assuming generic types validate runtime data

Generics operate within TypeScript's static type system. They do not automatically validate API responses or other external values at runtime.

Best Practices for TypeScript Generics

  • Use generics when one implementation should support different types without losing type information.
  • Choose descriptive type parameter names when a generic declaration becomes complex.
  • Let TypeScript infer type arguments when the intended types are clear.
  • Use constraints to specify the properties or capabilities that an implementation requires.
  • Use keyof and indexed access types when working with generic object properties.
  • Apply generic interfaces and classes to genuinely reusable data structures.
  • Avoid generics that add complexity without improving safety or reusability.
  • Validate external data at runtime even when a generic type describes its expected shape.

Conclusion

Generics allow TypeScript developers to create reusable, type-safe functions, interfaces, and classes. By using type parameters, constraints, multiple generic arguments, and default types, you can build flexible abstractions while preserving meaningful type relationships.

Start with simple generic functions and arrays, then practise constraints, keyof, generic interfaces, classes, and asynchronous wrappers. Use generics when they make code more reusable without weakening type safety or introducing unnecessary complexity. These skills form an important foundation for writing scalable TypeScript applications and libraries.

Code Examples

Basic Generic Function

typescript
function identity<T>(value: T): T {
  return value;
}

const courseName = identity("TypeScript");
const courseId = identity(101);
const isPublished = identity(true);

console.log(courseName);
console.log(courseId);
console.log(isPublished);
    

The generic parameter T allows the function to work with different input types while preserving the corresponding return type.

Generic Function with Arrays

typescript
function getFirstItem<T>(
  items: T[]
): T | undefined {
  return items[0];
}

console.log(getFirstItem([10, 20, 30]));
console.log(getFirstItem(["HTML", "CSS", "TypeScript"]));
console.log(getFirstItem([]));
    

The function works with arrays of different element types. Its return type includes undefined because an empty array does not have a first element.

Generic Constraints

typescript
interface HasLength {
  length: number;
}

function getLength<T extends HasLength>(
  value: T
): number {
  return value.length;
}

console.log(getLength("TypeScript"));
console.log(getLength([10, 20, 30]));
console.log(getLength({ length: 5 }));

// Compile-time error:
// getLength(100);
    

The extends constraint guarantees that accepted values provide a numeric length property, allowing the function to access it safely.

Generic Property Access with keyof

typescript
function getProperty<T, K extends keyof T>(
  object: T,
  key: K
): T[K] {
  return object[key];
}

const course = {
  id: 101,
  title: "TypeScript Fundamentals",
  published: true
};

const title = getProperty(course, "title");
const id = getProperty(course, "id");

console.log(title);
console.log(id);

// Compile-time error:
// getProperty(course, "price");
    

The keyof constraint restricts the selected key to a property that actually exists on the object, while T[K] preserves the property's value type.

Generic Interface for API Responses

typescript
interface ApiResponse<T> {
  success: boolean;
  data: T;
  message: string;
}

const courseResponse: ApiResponse<string[]> = {
  success: true,
  data: ["HTML", "CSS", "TypeScript"],
  message: "Courses loaded"
};

const countResponse: ApiResponse<number> = {
  success: true,
  data: 12,
  message: "Count loaded"
};

console.log(courseResponse.data);
console.log(countResponse.data);
    

A generic interface defines a reusable response structure while allowing its data property to retain the specific type associated with each response.

Generic Class

typescript
class Box<T> {
  constructor(public value: T) {}

  getValue(): T {
    return this.value;
  }

  setValue(value: T): void {
    this.value = value;
  }
}

const numberBox = new Box(100);
const textBox = new Box("TypeScript");

numberBox.setValue(200);
textBox.setValue("Advanced TypeScript");

console.log(numberBox.getValue());
console.log(textBox.getValue());
    

A generic class preserves the value type for each instance, allowing the same class implementation to safely manage different kinds of data.

Pro Tip

Use generics when the type of a value should remain connected across inputs, outputs, or data structures. Prefer inference for straightforward calls, add constraints when your implementation needs specific properties, and avoid using any when a generic can preserve type safety.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.