0Pricing
TypeScript Academy · Lesson

Component generics — intro

Build reusable components with type parameters, constraints, and inference; pass typed render props and keys safely.

Intro

Goal: Make one component work for many data shapes using <T>. You will pass a typed render prop, constrain keys, and let TypeScript infer T from usage.

  • Generic props and render functions
  • Constraints with extends
  • Key extraction without any

Generic List<T>

A generic List<T> keeps items and render aligned. Consumers can pass any T; inference works when T is obvious.

import React from "react"

type ListProps<T> = { items: T[]; render: (item: T, index: number) => React.ReactNode }

export function List<T>({ items, render }: ListProps<T>) {
  return <div style={{ display: "grid", gap: 6 }}>{items.map(render)}</div>
}

export default function App() {
  return (
    <div style={{ display: "grid", gap: 12 }}>
      <List<number> items={[1,2,3]} render={(n) => <span>#{n}</span>} />
      <List<{ id: string; name: string }>
        items={[{ id: "u1", name: "Ada" }, { id: "u2", name: "Lin" }]}
        render={(u) => <strong>{u.name}</strong>}
      />
    </div>
  )
}

All lessons in this course

  1. Props & children; event handlers; refs
  2. State & reducers; Context typing
  3. Component generics — intro
← Back to TypeScript Academy