0
0
Typescriptprogramming~5 mins

Generic class syntax in Typescript

Choose your learning style9 modes available
Introduction

Generic classes let you create flexible blueprints that work with many types, not just one. This helps you reuse code easily.

When you want a class to work with different data types without rewriting it.
When building containers like lists or stacks that hold any kind of item.
When you want to keep type safety but still be flexible.
When creating utility classes that can handle various data types.
When you want to avoid code duplication for similar classes with different types.
Syntax
Typescript
class ClassName<T> {
  property: T;
  constructor(value: T) {
    this.property = value;
  }
  method(): T {
    return this.property;
  }
}

The <T> after the class name means this class uses a generic type called T.

You can use T inside the class to represent any type given when creating an object.

Examples
This class Box holds one item of any type and returns it.
Typescript
class Box<T> {
  content: T;
  constructor(value: T) {
    this.content = value;
  }
  getContent(): T {
    return this.content;
  }
}
Here we create two boxes: one for numbers and one for strings.
Typescript
const numberBox = new Box<number>(123);
const stringBox = new Box<string>("hello");
This class uses two generic types T and U to hold two different types of values.
Typescript
class Pair<T, U> {
  first: T;
  second: U;
  constructor(first: T, second: U) {
    this.first = first;
    this.second = second;
  }
}
Sample Program

This program creates a generic Storage class that can store items of any type. We make one storage for numbers and one for strings, add items, and print them.

Typescript
class Storage<T> {
  private items: T[] = [];

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

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

const numberStorage = new Storage<number>();
numberStorage.add(10);
numberStorage.add(20);
console.log(numberStorage.getAll());

const stringStorage = new Storage<string>();
stringStorage.add("apple");
stringStorage.add("banana");
console.log(stringStorage.getAll());
OutputSuccess
Important Notes

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

Generic classes help catch type errors early because TypeScript knows what type you expect.

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

Summary

Generic classes let you write flexible, reusable code that works with many types.

Use <T> after the class name to declare a generic type.

Generic types keep your code safe and clear by knowing what type is used.