0
0
Typescriptprogramming~5 mins

Generic interface for collections in Typescript

Choose your learning style9 modes available
Introduction

We use generic interfaces to create flexible collection types that can hold any kind of data. This helps us write reusable and safe code.

When you want to create a list that can store numbers, strings, or any other type without rewriting code.
When you need a collection interface that works with different data types in your app.
When you want to ensure type safety while working with arrays or lists of items.
When building reusable components or libraries that handle collections of various types.
Syntax
Typescript
interface Collection<T> {
  add(item: T): void;
  remove(item: T): void;
  getAll(): T[];
}

The <T> means this interface works with any type you choose.

Methods use T to refer to the type of items in the collection.

Examples
This is the generic interface definition for a collection of items of type T.
Typescript
interface Collection<T> {
  add(item: T): void;
  remove(item: T): void;
  getAll(): T[];
}
This class uses the generic interface for a collection of numbers.
Typescript
class NumberCollection implements Collection<number> {
  private items: number[] = [];
  add(item: number): void { this.items.push(item); }
  remove(item: number): void { this.items = this.items.filter(i => i !== item); }
  getAll(): number[] { return this.items; }
}
This class uses the generic interface for a collection of strings.
Typescript
class StringCollection implements Collection<string> {
  private items: string[] = [];
  add(item: string): void { this.items.push(item); }
  remove(item: string): void { this.items = this.items.filter(i => i !== item); }
  getAll(): string[] { return this.items; }
}
Sample Program

This program creates a collection for numbers, adds three numbers, removes one, and then prints the remaining numbers.

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

class NumberCollection implements Collection<number> {
  private items: number[] = [];

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

  remove(item: number): void {
    this.items = this.items.filter(i => i !== item);
  }

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

const numbers = new NumberCollection();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.remove(20);
console.log(numbers.getAll());
OutputSuccess
Important Notes

Generic interfaces help keep your code flexible and safe by working with any data type.

Always specify the type when using the generic interface to avoid errors.

Summary

Generic interfaces let you create reusable collection types for any data.

Use <T> to represent the type inside the interface.

Implement the interface with specific types like number or string to use it.