Subscribe
How to Use Generics in Node.js TypeScript
5 mins read

By: vishwesh

How to Use Generics in Node.js TypeScript

Generics are a powerful feature of TypeScript that allow you to write reusable and type-safe code. If you're working with Node.js and TypeScript, you can take advantage of generics to make your code more flexible and maintainable. In this article, we'll explore how to use generics in Node.js TypeScript and demonstrate some practical examples.

What Are Generics?

Generics are a way to define a type or function that can work with multiple types. Instead of specifying a concrete type, you use a placeholder type parameter that can be substituted with a specific type at runtime. This allows you to write code that is more generic and reusable, without sacrificing type safety.

For example, consider the following TypeScript function that adds two numbers together:

function add(a: number, b: number): number {
  return a + b;
}

This function works well for adding two numbers together, but it's not very generic. If you wanted to add two strings together, you would need to write a separate function. This is where generics come in handy. You can define a generic function that can work with any type that supports the + operator:

function add<T extends string | number>(a: T, b: T): T {
  return a + b;
}

In this example, we've defined a type parameter T that extends either string or number. This means that we can pass in any string or number type, and the function will return the same type. This makes our code more generic and reusable.

Using Generics in Node.js

Now that we know what generics are, let's explore how to use them in Node.js TypeScript. There are several ways to use generics in Node.js, including:

  • Defining generic functions
  • Creating generic classes
  • Using generic types

Defining Generic Functions

Defining a generic function in Node.js is similar to defining a regular function, except that you use a type parameter to specify the type of the input and output. Here's an example of a generic function that takes an array of T type and returns the first element:

function getFirst<T>(arr: T[]): T {
  return arr[0];
}

In this example, we've defined a type parameter T that represents the type of the array. The function takes an array of T type and returns the first element of the array.

Creating Generic Classes

In addition to generic functions, you can also create generic classes in Node.js. A generic class allows you to define a class that can work with multiple types. Here's an example of a generic class that takes a T type and stores it in a private property:

class Box<T> {
  private item: T;

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

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

In this example, we've defined a type parameter T that represents the type of the item. The Box class takes an item of T type and stores it in a private property. The getItem method returns the stored item.

Using Generic Types

Finally, you can use generic types in Node.js to define reusable types that can work with multiple types. Here's an example of a generic type that represents a dictionary of T type:

type Dictionary<T> = {
  [key: string]: T;
};

In this example, we've defined a type parameter T that represents the type of the dictionary value. The Dictionary type represents a dictionary of T type, where the keys are strings.

Practical Examples

Now that we've covered the basics of using generics in Node.js TypeScript, let's explore some practical examples.

Example 1: Creating a Generic Cache

Imagine you're building a Node.js application that needs to cache some data. You could create a cache object that stores the data in memory, but you want to make it generic so that it can work with any type of data.

Here's an example of a generic cache implementation:

class Cache<T> {
  private data: Dictionary<T> = {};

  set(key: string, value: T): void {
    this.data[key] = value;
  }

  get(key: string): T | undefined {
    return this.data[key];
  }

  clear(): void {
    this.data = {};
  }
}

In this example, we've defined a generic Cache class that stores data in a dictionary. The set method allows you to set a key-value pair in the cache, the get method allows you to retrieve a value by key, and the clear method allows you to clear the entire cache.

Example 2: Creating a Generic Repository

Imagine you're building a Node.js application that needs to interact with a database. You could create a repository object that handles all the database interactions, but you want to make it generic so that it can work with any type of data.

Here's an example of a generic repository implementation:

class Repository<T> {
  private data: T[] = [];

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

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

  getById(id: number): T | undefined {
    return this.data.find((item) => item.id === id);
  }

  update(id: number, newItem: T): void {
    const index = this.data.findIndex((item) => item.id === id);
    this.data[index] = newItem;
  }

  delete(id: number): void {
    const index = this.data.findIndex((item) => item.id === id);
    this.data.splice(index, 1);
  }
}

In this example, we've defined a generic Repository class that stores data in an array. The add method allows you to add an item to the repository, the getAll method returns all the items in the repository, the getById method allows you to retrieve an item by id, the update method allows you to update an item by id, and the delete method allows you to delete an item by id.

Conclusion

Generics are a powerful feature of TypeScript that allow you to write generic and reusable code without sacrificing type safety. In this article, we've explored how to use generics in Node.js TypeScript and demonstrated some practical examples. Whether you're working with caching, repositories, or any other type of data, generics can help you write more flexible and maintainable code.

Recent posts

Don't miss the latest trends

    Popular Posts

    Popular Categories