React Component Typing

Building bulletproof React components.

TypeScript4 min readConcept 51 of 54

Typing Props

In modern React, we use TypeScript interface or type definitions to strictly define what props a component accepts.

But the real magic happens when you use **Generics** to create polymorphic components (like a Table that can render *any* data type while keeping strict type safety).

The Reusability Problem

If you build a <Table> component typed specifically for a User[], you can't reuse it for a Product[]. If you type the data as any[], you lose all autocompletion when trying to render a row.

By passing a type variable <T> to the component props, the Table dynamically molds itself to whatever array you pass into it.

Syntax

tsx import { ReactNode } from "react"; interface TableProps<T> { data: T[]; renderRow: (item: T) => ReactNode; } // Notice the trailing comma <T,> - it prevents the // JSX parser from confusing it with an HTML tag! export function Table<T,>({ data, renderRow }: TableProps<T>) { return ( <div>{data.map((item, i) => renderRow(item))}</div> ); }

Try it

Pass different data arrays to the generic <Table> component and watch how TypeScript instantly infers the correct types for the renderRow callback prop.

Pass Data to <Table>:
// Generic polymorphic component
export function Table<T,>({ data, renderRow }: TableProps<T>) { ... }

// TS automatically infers T based on the data array!
<Table
data={users}
renderRow={(item) => (
item.
name
Inferred as User
)} />
Generic Type Inference
1. Data Type Passed
{ name: string }[]
2. Inferred Callback Arg (item)
(item) => ...T = User
Click the autocomplete popup in the code!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Why must you sometimes write `<T,>` when defining a generic arrow function in a `.tsx` file?

Remember this

  • Use Generics <T> to create highly reusable React components.
  • A generic <Table data={users}> will automatically infer that T is User.
  • In .tsx arrow functions, use <T,> to avoid JSX parsing errors.
  • Stop using React.FC—type your function parameters directly.

Done with this concept?

Mark it complete to track your progress. No login needed.