0
0
Typescriptprogramming~5 mins

Generic interface declaration in Typescript

Choose your learning style9 modes available
Introduction

Generic interfaces let you create flexible blueprints that work with many types, not just one. This helps you write code that can handle different data without repeating yourself.

When you want a structure to hold different types of data but keep the same shape.
When building reusable components that can work with numbers, strings, or any other type.
When you want to ensure type safety but still keep your code flexible.
When defining APIs or libraries that should work with many data types.
When you want to avoid writing multiple interfaces for similar data shapes.
Syntax
Typescript
interface InterfaceName<T> {
  property: T;
  method(param: T): T;
}

The <T> after the interface name means it uses a generic type called T.

You can use any name instead of T, but T is common and stands for 'Type'.

Examples
This interface Box holds one property content of any type T.
Typescript
interface Box<T> {
  content: T;
}
This interface Pair uses two generic types T and U for two properties.
Typescript
interface Pair<T, U> {
  first: T;
  second: U;
}
This interface Result has a boolean success and a generic data of type T.
Typescript
interface Result<T> {
  success: boolean;
  data: T;
}
Sample Program

This program defines a generic interface Container with a type T. Then it creates a class NumberContainer that uses number as the type. It stores a number and returns it with getValue. Finally, it prints the stored number.

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;
  }
}

const myNumber = new NumberContainer(42);
console.log(myNumber.getValue());
OutputSuccess
Important Notes

Generic interfaces help keep your code DRY (Don't Repeat Yourself) by reusing the same structure for different types.

You can use multiple generic types separated by commas, like <T, U>.

When implementing a generic interface, you must specify the actual type to use.

Summary

Generic interfaces let you create flexible and reusable blueprints for data.

Use <T> to declare a generic type in an interface.

Implementations must specify the actual type to use with the generic interface.