0
0
Typescriptprogramming~5 mins

Why generic interfaces matter in Typescript

Choose your learning style9 modes available
Introduction

Generic interfaces let us write flexible code that works with many types without repeating ourselves.

When you want one interface to work with different data types.
When you want to avoid writing the same interface for each type.
When you want to keep your code easy to change and maintain.
When you want to create reusable components or functions.
When you want to catch type errors early while keeping flexibility.
Syntax
Typescript
interface InterfaceName<T> {
  property: T;
  method(param: T): T;
}

The <T> is a placeholder for any type you choose later.

You can use any name instead of T, but T is common.

Examples
This interface Box can hold any type of content.
Typescript
interface Box<T> {
  content: T;
}
This Result interface can wrap any type of data with a success flag.
Typescript
interface Result<T> {
  success: boolean;
  data: T;
}
This interface uses two generic types to hold two different values.
Typescript
interface Pair<T, U> {
  first: T;
  second: U;
}
Sample Program

This program shows how one generic interface Container<T> can be used for different types like number and string. It avoids writing separate interfaces for each type.

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

class NumberContainer implements Container<number> {
  value: number;
  constructor(value: number) {
    this.value = value;
  }
  getValue(): number {
    return this.value;
  }
}

class StringContainer implements Container<string> {
  value: string;
  constructor(value: string) {
    this.value = value;
  }
  getValue(): string {
    return this.value;
  }
}

const numBox = new NumberContainer(123);
const strBox = new StringContainer("hello");

console.log(numBox.getValue());
console.log(strBox.getValue());
OutputSuccess
Important Notes

Generic interfaces help keep your code DRY (Don't Repeat Yourself).

They improve code readability and type safety.

You can combine generics with classes, functions, and other interfaces.

Summary

Generic interfaces let you write one interface for many types.

They make your code flexible and reusable.

They help catch errors early by checking types.