Generics in JavaScript: Why They Are Needed and How to Use Them for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why Do You Need Generics in JavaScript?

Every JavaScript developer sooner or later encounters a situation where a function or class must work with different data types. Without special tools, you either have to duplicate code or use any, which deprives you of type control. Generics solve this problem.

In the context of JavaScript, generics are especially relevant when working with TypeScript or when using modern patterns in Node.js. Even if you write in pure JavaScript, understanding the concept of Generics will help you write more flexible and safer code.

In this article, we will cover:

  • What Generics are and why they are needed
  • How to use generics in functions and classes
  • Practical examples for Node.js
  • Common beginner mistakes


What Are Generics in JavaScript?

Generics are a way to create components (functions, classes, interfaces) that can work with different data types while maintaining type safety. Instead of writing a separate function for numbers, a separate one for strings, and a separate one for objects, you write one universal function.

Imagine you are creating a box. A regular box can only store one type of item. Generics are a "smart" box that adapts to what you put inside, but at the same time remembers what exactly is in there.

In TypeScript (a superset of JavaScript), generics are denoted by angle brackets <> and the letter T (for Type) or other identifiers:



// Simplest example of a generic in TypeScriptfunction identity<T>(arg: T): T {    return arg;}

// Now the function works with any typeconst num = identity<number>(42); // type numberconst str = identity<string>("Hello"); // type string


In pure JavaScript, this syntax is not available, but the concept remains useful for understanding application architecture.



Why Are Generics Needed in JavaScript and Node.js?

Let's look at three key reasons why it's worth understanding generics.



1. Type Safety Without Losing Flexibility

Without generics, you often use any, which disables type checking:

// Bad: we lose type informationfunction getFirstElement(arr: any[]): any {    return arr[0];}

const val = getFirstElement([1, 2, 3]);// val has type any, we don't know if it's a number or string

With generics, the type is preserved:

// Good: the type is preservedfunction getFirstElement<T>(arr: T[]): T {    return arr[0];}

const val = getFirstElement([1, 2, 3]); // val: numberconst str = getFirstElement(["a", "b"]); // str: string


2. Reducing Code Duplication

Without generics, you would have to write separate functions for each type:

// Without generics — duplicationfunction processNumber(num: number): number { /* ... */ }function processString(str: string): string { /* ... */ }function processObject(obj: object): object { /* ... */ }

// With generics — one functionfunction process<T>(data: T): T { /* ... */ }


3. Creating Reusable Components

In Node.js, generics are often used to create universal utilities, data handlers, and API clients:

// Universal HTTP client with genericsasync function fetchData<T>(url: string): Promise<T> {    const response = await fetch(url);    return response.json() as Promise<T>;}

// Usageinterface User { id: number; name: string;}

const user = await fetchData<User>('/api/user/1');// user automatically has type User


How to Use Generics: Practical

Blogs

Book Recommendations