Settle in
 ·  4 min read

TypeScript Generics in React: Code Cleanliness and Type Safety

How TypeScript generics help you build reusable, type-safe React components without duplicating code or falling back to any.

Have you ever encountered a situation where you had a function handling different data types and, as a result, ended up writing separate functions or classes for each type or resorting to using any keyword to manage uncertain data? If so, you are not alone. In this article, we will explore a powerful feature of TypeScript called generics that provides an elegant solution to the problem we faced earlier. Generics enable us to write reusable and future-proof code, eliminating the need for repetitive code blocks tailored to specific data types. So Let’s delve into it.

Generics in TypeScript

In TypeScript, Generics refers to a feature that allows you to create reusable components and functions that work with different types. Generics enable you to define placeholders for types, which can be filled in later when the component or function is used. It enhances type safety and code reusability by providing flexibility without sacrificing type checking.

Without Generics:

function firstAndLast(array: any[]) {
  const first = array[0];
  const last = array[array.length - 1];
  return [first, last];
}

// Usage example
const numbers = [1, 2, 3, 4, 5];
const result = firstAndLast(numbers);
console.log(result); // Output: [1, 5]

In this example, the function firstAndLast takes an array of any type, which means it can accept an array of elements of any type but does not provide any type safety.

With Generics:

function firstAndLast<T>(array: T[]): [T, T] {
	const first = array[0];
	const last = array[array.length - 1];
	return [first, last];
}

// Usage example
const numbers = [1, 2, 3, 4, 5];
const result = firstAndLast(numbers);
console.log(result); // Output: [1, 5]

const superheroes = ['superman', 'batman', 'ironman'];
const result2 = firstAndLast(superheroes);
console.log(result2); // Output: ['superman', 'ironman']

In the above example, the function firstAndLast uses a generic type parameter T, which allows the function to work with arrays of any specific type. This provides type safety, and the return type is inferred as [T, T], indicating that the first and last elements of the array will have the same type as the array’s elements.

Example with React

import React from "react";

// Define a type alias 'SelectItem' that represents the allowed types for the options in the Select component.
type SelectItem = string | number | readonly string[] | undefined;

interface SelectProps<T extends SelectItem> {
  options: T[];
  value: T;
  onChange: (value: T) => void;
}

function Select<T extends SelectItem>({
  options,
  value,
  onChange,
}: SelectProps<T>) {
  const handleChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const selectedValue = event.target.value as T;
    onChange(selectedValue);
  };

  return (
    <select value={value} onChange={handleChange}>
      {options.map((option, index) => (
        <option key={index} value={option}>
          {option}
        </option>
      ))}
    </select>
  );
}

The code defines a generic Select component that takes a type parameter T constrained to the union type SelectItem. The SelectItem type alias represents the allowed types for the options in the component. The SelectProps interface defines the components’ properties, including an array of options, the currently selected value, and a callback to update the selected value.

function App() {
	const [selectedFruit, setSelectedFruit] = (React.useState < string) > 'apple';
	const [selectedNumber, setSelectedNumber] = (React.useState < number) > 1;

	const fruits = ['apple', 'banana', 'orange'];
	const numbers = [1, 2, 3, 4, 5];

	return (
		<div>
			<Select options={fruits} value={selectedFruit} onChange={setSelectedFruit} />
			<Select options={numbers} value={selectedNumber} onChange={setSelectedNumber} />
		</div>
	);
}

export default App;

In the above code, The Select component is used twice in the App component to create two dropdowns. The first Select component is for selecting fruits, and the second one is for selecting numbers. By doing so, the Select component can handle different types of data (strings and numbers) in a type-safe manner, ensuring the selected value matches the specified data type. The App component showcases the flexibility and reusability of the Select component, making it a powerful tool for creating dropdowns to select various types of data in React applications.

Benefits:

  1. Type Safety: Generics allow you to maintain type safety while working with different data types. It helps catch type-related errors at compile-time rather than runtime, leading to more robust and reliable code.
  2. Reusability: Generics enable you to create functions, classes, and interfaces that can work with various data types. It promotes code reusability, reducing the need to duplicate logic for different types.
  3. Cleaner Code: You can write more concise and cleaner code since you avoid redundant or repetitive code blocks tailored to specific data types.
  4. Abstraction: Generics provide a level of abstraction, allowing you to create flexible and adaptable components without being tightly bound to specific data types.
  5. Future-Proofing: As your codebase evolves, generics can help accommodate new data types without modifying existing code, making your application more adaptable.

I hope you find this article helpful. And I encourage you to use generics to build more reusable and type-safe components for your projects.

Stay curious; Keep coding.


This post was originally published on Medium.