TypeScript Functions and Generics for React Code

Type callback and event handlers, use inference well, and build reusable React helpers and components with TypeScript generics and safe constraints.

published: reading time: 7 min read author: Geek Workbench
Quick Summary

Typed callbacks state what a function accepts and returns, while generics keep a helper’s input and output types connected across different data. React provides event types for JSX handlers, and extracted handlers can name their event type explicitly. This guide also shows when a generic constraint helps, when a concrete signature reads better, and why runtime input still needs validation.

TypeScript Functions and Generics for React Code

Introduction

Callbacks connect React components to app behavior. TypeScript describes their inputs and returns; generics let one helper work across data types without losing type information.

This article covers callback and event signatures, inference, and constraints for reusable helpers and components.

Without a generic, you might write separate helpers for string IDs and number IDs. This version keeps the input and return types connected:

function last<T>(items: readonly T[]): T | undefined {
  return items[items.length - 1];
}

const lastId = last(["a-17", "a-18"]); // string | undefined

Type callbacks and events

Type an event handler with the React event for its element. Pass a smaller domain value through props when the parent does not need the original browser event:

import type { ChangeEvent } from "react";

interface SearchBoxProps {
  onQueryChange: (query: string) => void;
}

function SearchBox({ onQueryChange }: SearchBoxProps) {
  const handleChange = (event: ChangeEvent<HTMLInputElement>): void => {
    onQueryChange(event.currentTarget.value);
  };

  return <input onChange={handleChange} />;
}

Here the component boundary accepts a string callback, while the extracted handler owns the input event type.

Let inference do its job

TypeScript infers an inline callback’s event from React’s onChange prop. In the last example above, the array values let TypeScript infer T as string, so the result is string | undefined without an explicit type argument. Add annotations for public contracts or where context is unclear; skip obvious local types.

Reuse behavior with generics

A generic keeps the input type connected to the return type: last receives an array of T and returns a T or undefined. readonly tells callers the helper will not change their list. Use generics when behavior stays the same across types, such as selecting an item or rendering a list. If one concrete type explains the function better, use it.

A constraint gives a generic the minimum shape it needs. This component accepts any item with an id and lets the caller define how to render it.

import type { ReactNode } from "react";

interface Keyed {
  id: string;
}

interface ItemListProps<T extends Keyed> {
  items: readonly T[];
  renderItem: (item: T) => ReactNode;
}

function ItemList<T extends Keyed>({ items, renderItem }: ItemListProps<T>) {
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>{renderItem(item)}</li>
      ))}
    </ul>
  );
}

The constraint allows id access while preserving each item’s other fields. In .tsx, <T,> distinguishes a generic arrow function from JSX; named functions avoid the ambiguity.

When to Use / When NOT to Use

Use a generic when the same behavior works for several data types and its input type should stay connected to its output. Avoid a type parameter when a function only handles one concrete model or callers need casts to make the generic fit; a concrete signature is clearer.

From event to reusable view

flowchart LR
  A[Input event] --> B[Typed callback]
  B --> C[Search query]
  C --> D[Generic result list]
  D --> E[Rendered item]

Production Failure Scenarios

A list keyed by array index can break after filtering: React may reuse a row and attach local state to another record. Require a stable identifier and use it as the key. If records lack one, assign identity at the data boundary.

An async callback passed where the UI expects synchronous work can reject without a handler. Wrap the async operation, catch the rejection, and expose a safe error state instead of leaving the user with no feedback.

Trade-Off Table

Approach Benefit Cost
Concrete function type Clear, easy to read Tied to one data shape
Generic helper Reuses behavior and preserves type details Adds syntax and can be harder to debug
Generic constraint Allows access to required fields Restricts which values are accepted
Type assertion Short workaround Hides mismatches without checking data

Common Pitfalls / Anti-Patterns

  • Using any or unchecked assertions to silence a mismatch rather than checking the value.
  • Passing a promise-returning function to a callback contract that expects a synchronous result.
  • Adding a generic parameter that does not preserve a useful relationship between inputs and outputs.

Observability Checklist

  • Track rejected async work by operation.
  • Include a safe record identifier in error reports.

Security and Compliance Notes

Types disappear at runtime, so validate API, URL, and storage values before trusting them. Generics preserve compile-time relationships; they do not validate input. Keep form contents and credentials out of logs.

Quick Recap Checklist

  • Type callbacks by their arguments and meaningful return values.
  • Use React’s specific event types when you need event fields.
  • Let inference fill in local types; annotate exported contracts.
  • Use generics when behavior stays the same across data types.
  • Add constraints for the fields a helper actually uses.

Interview Questions

1. What does a generic preserve that `any` loses?
A generic keeps the input/output connection. A helper can accept string[] and return string | undefined; any loses that information.
2. Why constrain a generic type?
T extends { id: string } permits safe access to id, preserves the rest of T, and rejects incompatible values.
3. Should every React callback be typed with a React event?
No. Expose a domain callback like (query: string) => void and translate the DOM event internally. Pass the event only when callers need it.
4. How can TypeScript infer a generic argument?
It often infers the type from the arguments passed to the call.
  • last(["a", "b"]) infers T as string.
  • Write the type argument explicitly only when inference is not clear or useful.
5. What does readonly add to a generic array parameter?
It tells callers that the function does not mutate the input array.
  • The helper can still read and return an item.
  • Mutation methods are unavailable through that parameter.
6. What is the purpose of a generic constraint?
It requires only the fields the implementation needs.
  • T extends Keyed allows safe use of id.
  • Other properties on the caller's item type remain available.
7. When is a concrete function signature clearer?
Use a concrete type when the function only supports one domain model.
  • It avoids a type parameter with no useful relationship.
  • Callers do not need to supply casts to make the abstraction work.
8. What does a callback's return type communicate?
It describes whether the caller can use a result from the callback.
  • Use void when the result is ignored.
  • Use a promise-returning contract when async completion is part of the API.
9. Why might a generic arrow function use <T,> in TSX?
The trailing comma helps the TSX parser read the angle brackets as type parameters.
  • Without it, the syntax can look like a JSX element.
  • A named generic function avoids that ambiguity.
10. Do generic types validate external data?
No. Generic types are checked at compile time and erased from JavaScript.
  • Validate API and storage values before passing them to a helper.
  • A generic constraint does not inspect runtime data.

Further Reading

Conclusion

Type callbacks clearly and let context provide obvious types. Use generics when they preserve relationships across data shapes, constrain them to needed fields, and validate external values at runtime.

Category

Related Posts

Accessible React UI: Semantics, Labels, and Keyboard Use

Build React interfaces with semantic controls, connected labels, visible keyboard focus, and status announcements through practical TypeScript examples.

#react #typescript #accessibility

Advanced React State: When Local State Stops Fitting

Learn when React state needs a reducer and context, when Redux Toolkit helps, and why server data often belongs in a query cache instead.

#react #typescript #state-management

Testing React Components and User Interactions

Write behavior-first React tests with accessible roles, realistic user events, and async assertions while avoiding brittle checks of implementation details.

#react #typescript #testing