2024-07-16

Understanding TypeScript Generics: Like You're 5 Years Old!

What are Generics?

Imagine you have a magic box. This box can hold anything you want—your favorite toy, a book, or even a snack! Generics in TypeScript are like that magic box. They allow you to create reusable functions, classes, or components that can work with any type of data.

Why Use Generics?

Let's say you have a toy box that only holds cars. But what if you want to store dolls or blocks too? You'd need separate boxes for each. Generics let you have one box for everything, making your code cleaner and more flexible.

Basic Example

Here's a simple example to understand generics:

function magicBox<T>(item: T): T {
  return item;
}

const toy = magicBox("Car");
const number = magicBox(5);
const isHappy = magicBox(true);

  • magicBox is our magic box.
  • <T> is a placeholder for any type.
  • item: T means the function takes an item of any type.
  • : T means the function returns an item of the same type.

In this example:

  • toy is a string ("Car").
  • number is a number (5).
  • isHappy is a boolean (true).

Using Generics in React

Now, let's see how we can use generics in a React component. Imagine we have a special box that can display any type of content.

Step 1: Create a Generic Component

First, we create a generic component called MagicBox.

import React from 'react';

interface MagicBoxProps<T> {
  item: T;
}

const MagicBox = <T,>({ item }: MagicBoxProps<T>) => {
  return (
    <div>
      <h2>This is a magic box!</h2>
      <p>{JSON.stringify(item)}</p>
    </div>
  );
};

export default MagicBox;

  • MagicBoxProps<T> defines the props for our component.
  • <T,> after const MagicBox tells TypeScript that this is a generic component.

Step 2: Use the Component

Now, let's use our MagicBox component with different types of items.

import React from 'react';
import MagicBox from './MagicBox';

const App = () => {
  return (
    <div>
      <MagicBox item="A toy car" />
      <MagicBox item={42} />
      <MagicBox item={{ name: "Doll", color: "Pink" }} />
    </div>
  );
};

export default App;

In the App component:

  • We use MagicBox with a string, a number, and an object.
  • The MagicBox component can handle all these types because it's generic!

Conclusion

Generics in TypeScript are like having a magic box that can hold anything. They make your code more flexible and reusable. In React, they allow you to create components that can work with different types of data, making your components more powerful.

Now, go ahead and create your own magic boxes with TypeScript generics! 🧙‍♂️✨