How Do Generic Interfaces Work in TypeScript?

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

Introduction to Generic Interfaces

Interfaces in TypeScript describe the structure that an object must satisfy. They define properties, methods, and other type requirements that help developers write predictable and maintainable code. However, an ordinary interface may become restrictive when the same object structure needs to work with different data types.

Generic interfaces solve this problem by allowing interfaces to accept type parameters. These parameters act as placeholders for types supplied when the interface is used. The same interface can describe objects containing strings, numbers, arrays, custom models, or other values without duplicating the interface definition.

Generic interfaces are especially useful for API responses, repositories, data containers, reusable service contracts, event handlers, and callback definitions. They help preserve type information throughout an application and allow different implementations to share a consistent structure.

1. Why Do We Need Generic Interfaces?

Imagine an application that returns course information and user information using objects with the same general structure. Both responses contain a success flag and a data property, but the data property holds different types of values.

Without generics, you might define separate interfaces for every response or use any for the data property. Separate interfaces can introduce duplication, while any removes valuable type checking.

interface CourseResponse {
  success: boolean;
  data: string[];
}

interface CountResponse {
  success: boolean;
  data: number;
}

const courses: CourseResponse = {
  success: true,
  data: ["HTML", "CSS", "TypeScript"]
};

const count: CountResponse = {
  success: true,
  data: 12
};

console.log(courses.data);
console.log(count.data);

These interfaces work, but their definitions repeat the same structure. A generic interface allows that shared structure to be defined once while letting each response specify its own data type.

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

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

const count: ApiResponse<number> = {
  success: true,
  data: 12
};

console.log(courses.data);
console.log(count.data);

The type parameter T represents the data type selected by the caller. ApiResponse<string[]> describes a response containing an array of strings, while ApiResponse<number> describes a response containing a number.

2. Creating a Generic Interface

To create a generic interface, declare one or more type parameters inside angle brackets after the interface name. Those parameters can then be used in properties, method signatures, and other parts of the interface definition.

interface Box<T> {
  value: T;
}

const numberBox: Box<number> = {
  value: 100
};

const stringBox: Box<string> = {
  value: "TypeScript"
};

const courseBox: Box<{ title: string }> = {
  value: {
    title: "TypeScript Fundamentals"
  }
};

console.log(numberBox.value);
console.log(stringBox.value);
console.log(courseBox.value.title);

The Box interface does not specify one fixed type for value. Instead, it uses T, which is replaced by the type argument supplied when the interface is applied.

Box<number> requires a number, Box<string> requires a string, and Box<{ title: string }> requires an object containing a string-valued title property.

TypeScript checks each object against its selected interface type. For example, assigning a string to the value property of a Box<number> object produces a compile-time error.

3. Generic Interfaces with Multiple Type Parameters

A generic interface can declare multiple type parameters when its properties represent different kinds of data. Each parameter can describe a separate part of the object's structure.

interface Pair<T, U> {
  first: T;
  second: U;
}

const coursePair: Pair<string, number> = {
  first: "TypeScript",
  second: 101
};

const userPair: Pair<number, boolean> = {
  first: 25,
  second: true
};

console.log(coursePair.first);
console.log(coursePair.second);

console.log(userPair.first);
console.log(userPair.second);

In Pair<T, U>, T represents the type of first and U represents the type of second. This allows the interface to represent different combinations without changing its definition.

Multiple generic parameters are useful for key-value records, request-response models, mapping structures, comparison results, and objects that combine related values of different types.

Use separate parameters when the types should be independently selectable. If two properties must always share the same type, reusing one parameter is usually more appropriate than declaring two unrelated parameters.

4. Generic Methods Inside Interfaces

Generic interfaces can define methods whose parameters and return values depend on the interface's type parameters. They can also define methods that introduce their own generic type parameters.

Consider a reusable storage contract whose main value type is T. The interface can require methods that store and retrieve values of that type.

interface Storage<T> {
  save(value: T): void;
  get(): T;
}

class StringStorage implements Storage<string> {
  private value = "";

  save(value: string): void {
    this.value = value;
  }

  get(): string {
    return this.value;
  }
}

const storage = new StringStorage();

storage.save("TypeScript");
console.log(storage.get());

Storage<T> describes a contract for saving and retrieving the same type of value. StringStorage implements Storage<string>, so its methods must accept and return strings.

Another implementation could use Storage<number> and store numeric values instead. Both implementations follow the same contract while maintaining their own specific data types.

This approach is useful when defining reusable storage, caching, data-processing, and repository contracts that need consistent behavior across multiple implementations.

5. Generic Interfaces with Constraints

Sometimes an interface should accept only types that satisfy a particular structure. Generic constraints allow you to specify that requirement using extends.

interface HasId {
  id: number;
}

interface Repository<T extends HasId> {
  getAll(): T[];
  getById(id: number): T | undefined;
}

interface Course extends HasId {
  title: string;
}

const courseRepository: Repository<Course> = {
  getAll() {
    return [
      { id: 1, title: "HTML" },
      { id: 2, title: "TypeScript" }
    ];
  },

  getById(id) {
    return this.getAll().find(
      course => course.id === id
    );
  }
};

console.log(courseRepository.getAll());
console.log(courseRepository.getById(2));

The Repository interface requires T to satisfy HasId. This guarantees that repository items contain a numeric id property, allowing implementations to define identifier-based lookup operations.

The Course interface satisfies the constraint because it extends HasId and adds a title property. Other domain models, such as users or products, could also use the repository contract if they provide a compatible id.

The return type T | undefined reflects that an item may not exist in the collection. The constraint guarantees the structure of an item, not that a requested record will always be found.

6. Generic Interfaces with Default Type Parameters

Generic interfaces can provide default type parameters. When a type argument is omitted and cannot be inferred from another context, TypeScript can use the declared default.

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

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

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

const coursesResult: Result<string[]> = {
  data: ["HTML", "CSS", "TypeScript"],
  success: true
};

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

Result<T = string> declares string as the default type. The first object uses the default, while the other objects explicitly choose number and string[].

Default type parameters can make common use cases simpler. They are especially useful when an interface is widely used and one type is a sensible default, but alternative types must remain available.

A default generic parameter changes the type selected by the compiler; it does not create a runtime default value or initialize the object's properties automatically.

7. Extending Generic Interfaces

An interface can extend a generic interface to inherit its properties and methods. When extending a generic interface, you can supply a concrete type argument or carry a generic parameter forward into the extended contract.

interface DataContainer<T> {
  data: T;
}

interface TimestampedContainer<T>
  extends DataContainer<T> {
  createdAt: Date;
}

const courseData: TimestampedContainer<string[]> = {
  data: ["HTML", "TypeScript"],
  createdAt: new Date()
};

console.log(courseData.data);
console.log(courseData.createdAt);

DataContainer<T> defines the generic data property. TimestampedContainer<T> extends that contract and adds a createdAt property while preserving the same data type.

The resulting interface can represent different kinds of timestamped data without duplicating the data property definition. For example, it can describe timestamped lists, objects, or primitive values.

Generic interface inheritance is useful for extending common response models, adding metadata to records, composing service contracts, and sharing foundational properties across related types.

8. Implementing Generic Interfaces in Classes

Classes can implement generic interfaces by supplying a type argument that determines the required types of their members. Alternatively, a class can declare its own generic parameter and pass it to the interface.

interface Repository<T> {
  add(item: T): void;
  getAll(): T[];
}

class MemoryRepository<T>
  implements Repository<T> {
  private items: T[] = [];

  add(item: T): void {
    this.items.push(item);
  }

  getAll(): T[] {
    return [...this.items];
  }
}

const courseRepository =
  new MemoryRepository<string>();

courseRepository.add("HTML");
courseRepository.add("CSS");
courseRepository.add("TypeScript");

console.log(courseRepository.getAll());

MemoryRepository<T> implements Repository<T> and carries the same generic type parameter into its implementation. This allows the class to store and return different types of data without creating separate implementations for each type.

The items property is private, so callers cannot access the internal array directly through normal TypeScript access checking. The getAll method returns a shallow copy, which prevents callers from directly changing the repository's array structure through the returned array.

The copy does not deep-clone stored objects. If T contains objects, references to those objects remain shared unless an explicit cloning strategy is implemented.

9. Generic Interfaces for API Responses

API response interfaces are a common practical application of generics. Different endpoints frequently use the same response structure while returning different data models.

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

interface User {
  id: number;
  name: string;
}

interface Course {
  id: number;
  title: string;
}

const userResponse: ApiResponse<User> = {
  success: true,
  data: {
    id: 1,
    name: "Asha"
  },
  message: "User loaded"
};

const courseResponse: ApiResponse<Course[]> = {
  success: true,
  data: [
    { id: 101, title: "TypeScript" },
    { id: 102, title: "JavaScript" }
  ],
  message: "Courses loaded"
};

console.log(userResponse.data.name);
console.log(courseResponse.data[0].title);

ApiResponse<T> describes a shared response contract, while each endpoint selects the type of its data property. The User response contains one user, whereas the Course response contains an array of courses.

This makes service methods easier to reuse because they can share response-handling logic without losing the specific data types returned by individual endpoints.

Remember that TypeScript interfaces are compile-time constructs. Declaring an API result as ApiResponse<User> does not validate incoming JSON at runtime. Data from external systems should be validated when its trustworthiness or correctness matters.

10. Generic Interfaces with Callback Functions

Generic interfaces can describe callback functions whose input or output types depend on a generic parameter. This is useful for reusable event handlers, data processors, transformation strategies, and configurable utilities.

interface Transformer<T, U> {
  transform: (value: T) => U;
}

const uppercaseTransformer: Transformer<string, string> = {
  transform(value) {
    return value.toUpperCase();
  }
};

const numberTransformer: Transformer<number, string> = {
  transform(value) {
    return String(value * 2);
  }
};

console.log(uppercaseTransformer.transform("typescript"));
console.log(numberTransformer.transform(25));

Transformer<T, U> represents an object containing a function that accepts T and returns U. The first implementation transforms a string into an uppercase string, while the second transforms a number into a string.

Because the callback signature is part of the interface, TypeScript can check that each implementation accepts the appropriate input and produces the correct output type.

This pattern is especially useful when a system accepts user-defined transformations while keeping a stable contract for how those transformations are called.

11. Generic Interfaces vs Generic Functions

Generic interfaces and generic functions both use type parameters, but they serve different purposes. A generic function applies type parameters to a function signature and its behavior. A generic interface describes a reusable structure that may contain properties, methods, or function signatures.

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

interface Holder<T> {
  value: T;
  getValue(): T;
}

const numberHolder: Holder<number> = {
  value: 101,

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

console.log(identity("TypeScript"));
console.log(numberHolder.getValue());

The identity function declares a generic type parameter for a single function call. The Holder interface describes a reusable object contract, and each Holder<T> value follows that contract for its selected type.

You can combine both features when designing reusable systems. For example, a generic interface may define a service contract, while generic functions inside its implementation process individual values using type parameters.

12. Common Mistakes When Using Generic Interfaces

Using any instead of a generic parameter

Using any for a data property allows unrelated types to pass through without useful checking. A generic parameter preserves the relationship between the interface and the actual data type.

Forgetting to supply a type argument

Generic interfaces without defaults often require an explicit type argument. Choose the intended data type when using the interface, or define a meaningful default when appropriate.

Declaring unnecessary generic parameters

Too many type parameters can make an interface harder to understand. Add generic parameters only when they represent meaningful differences or relationships between types.

Using constraints that are too restrictive

A constraint should specify the minimum structure required by the interface. An unnecessarily narrow constraint can prevent other compatible models from reusing the same contract.

Assuming interfaces validate runtime data

Interfaces and generic arguments do not automatically validate data received from an API or external file. Runtime validation is a separate responsibility.

Best Practices for Generic Interfaces

  • Use generic interfaces when a common object structure needs to represent multiple data types.
  • Choose descriptive type parameter names when interfaces contain multiple generic arguments.
  • Use constraints to guarantee the minimum properties or capabilities required by a contract.
  • Define default generic types only when they represent sensible defaults for common use cases.
  • Use interface inheritance to extend shared structures without duplicating properties.
  • Implement generic interfaces in classes to establish consistent contracts across different implementations.
  • Use accurate return types, including undefined when a lookup result may be absent.
  • Validate external data at runtime when the application depends on its actual structure.

Conclusion

Generic interfaces allow TypeScript developers to define reusable contracts without fixing every property to one concrete data type. They support generic properties, methods, callbacks, multiple type parameters, constraints, default types, and interface inheritance.

Practise with data containers, API response models, repository contracts, and generic class implementations to understand how these interfaces work in real applications. By designing clear generic contracts, you can reduce duplicated definitions, preserve type safety, and make TypeScript applications easier to maintain as their data models evolve.

Code Examples

Basic Generic Interface

typescript
interface Box<T> {
  value: T;
}

const numberBox: Box<number> = {
  value: 100
};

const stringBox: Box<string> = {
  value: "TypeScript"
};

console.log(numberBox.value);
console.log(stringBox.value);
    

The generic Box interface can store different value types while enforcing the selected type for each instance.

Generic Interface with Multiple Type Parameters

typescript
interface Pair<T, U> {
  first: T;
  second: U;
}

const coursePair: Pair<string, number> = {
  first: "TypeScript",
  second: 101
};

const userPair: Pair<number, boolean> = {
  first: 25,
  second: true
};

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

Separate generic parameters allow each property to have its own independently selected type.

Generic Interface with Constraints

typescript
interface HasId {
  id: number;
}

interface Repository<T extends HasId> {
  getAll(): T[];
  getById(id: number): T | undefined;
}

interface Course extends HasId {
  title: string;
}

const repository: Repository<Course> = {
  getAll() {
    return [
      { id: 1, title: "HTML" },
      { id: 2, title: "TypeScript" }
    ];
  },

  getById(id) {
    return this.getAll().find(course => course.id === id);
  }
};

console.log(repository.getAll());
console.log(repository.getById(2));
    

The constraint guarantees that repository items contain an id property, while T preserves the complete course type.

Generic Interface with a Default Type

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

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

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

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

The default generic parameter makes string the default data type, while callers can explicitly choose another type.

Generic Interface Implemented by a Class

typescript
interface Storage<T> {
  save(value: T): void;
  get(): T;
}

class MemoryStorage<T> implements Storage<T> {
  private value!: T;

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

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

const storage = new MemoryStorage<string>();

storage.save("TypeScript");
console.log(storage.get());
    

The class carries the interface type parameter into its implementation, ensuring that save and get operate on the same type.

Generic Interface with a Callback

typescript
interface Transformer<T, U> {
  transform: (value: T) => U;
}

const uppercaseTransformer: Transformer<string, string> = {
  transform(value) {
    return value.toUpperCase();
  }
};

const numberTransformer: Transformer<number, string> = {
  transform(value) {
    return String(value * 2);
  }
};

console.log(uppercaseTransformer.transform("typescript"));
console.log(numberTransformer.transform(25));
    

The interface describes a callback with a defined input type and output type, enabling different transformations to share one contract.

Pro Tip

Use generic interfaces when multiple objects share the same structure but contain different data types. Combine them with extends for required capabilities, keyof for type-safe property access, and interface inheritance for reusable contracts. Remember that generic types provide compile-time guarantees, not runtime data validation.

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.