Generic Functions, Classes, and Interfaces in TypeScript

TypeScript, as a statically typed superset of JavaScript, brings numerous enhancements to the existing type system. One of the most powerful features TypeScript provides is generics, which allow developers to write reusable code components that work with different types.

Generic Functions

Generic functions enable us to define a single function declaration that can work with various types. These functions are written using a type parameter, which represents a placeholder for the actual type that will be provided when calling the function. Here's an example:

function merge<T>(array1: T[], array2: T[]): T[] {
  return [...array1, ...array2];
}

In the above code, the merge function takes two arrays of type T and returns an array of the same type T. The type T allows us to use any valid type when invoking the function, and the function will ensure type safety during execution.

Generic Classes

Just like functions, classes can also be made generic in TypeScript. This allows us to create reusable class definitions that can work with different types. Here's an example:

class Container<T> {
  private item: T;

  constructor(item: T) {
    this.item = item;
  }

  getItem(): T {
    return this.item;
  }
}

In the Container class, the type parameter T is used to denote the type of item. By doing so, we can create instances of Container with different types and ensure that the type safety is maintained.

Generic Interfaces

Interfaces in TypeScript can also be made generic, similar to functions and classes. This provides flexibility when defining contracts and allows for reusable components. Let's see an example:

interface Repository<T> {
  getById(id: string): T;
  getAll(): T[];
  create(item: T): void;
  update(id: string, item: T): void;
  delete(id: string): void;
}

In the above code snippet, the Repository interface is defined with a generic type parameter T. This allows different implementations of the interface to specify the specific type they work with while adhering to the contract defined by the interface.

Conclusion

Generic functions, classes, and interfaces are powerful tools in TypeScript that enable developers to write reusable and type-safe code. By leveraging generics, we can create components that are flexible, adaptable, and maintain type safety throughout the codebase. So, the next time you find yourself writing similar code for different types, consider using generics to make your code more reusable and efficient.


noob to master © copyleft