This practical TypeScript with React guide gives you a repeatable way to type component props, children, DOM events, refs, and generic components without falling back to any. Use the checklists and copyable templates whenever you create a component or change its public API.
Overview
Good React types describe the contract between a component and its callers. That contract includes which props are required, which values are allowed, what an event handler receives, whether children are supported, and which element or component a ref points to. Start with the public API rather than the component implementation, then let TypeScript guide the internal details.
A useful workflow is:
- Write down the component's public props and required behavior.
- Choose the narrowest useful types for values, callbacks, and children.
- Type the component implementation from those props.
- Add event and ref types at the point where they enter the component.
- Test the intended usage, including invalid usage that should fail to compile.
Prefer types that express intent. For example, a button that only accepts a small set of visual variants should use a union such as 'primary' | 'secondary', not an unrestricted string. Conversely, do not duplicate a large native element API when React already exposes the relevant types.
| Scenario | Recommended pattern | Example |
|---|---|---|
| Required and optional values | An explicit props type | type Props = { title: string; compact?: boolean } |
| Component children | ReactNode or a narrower type | children?: ReactNode |
| Native element props | React's element-specific prop type | ButtonHTMLAttributes<HTMLButtonElement> |
| DOM events | Element-specific React event types | ChangeEvent<HTMLInputElement> |
| Element refs | Ref or RefObject for the target element | Ref<HTMLInputElement> |
| Reusable data components | A generic props type | List<T> with items: T[] |
Checklist by scenario
Typing ordinary component props
Define a named props type when the component has more than one or two values, or when the contract deserves a readable name. Keep optional props genuinely optional and give defaults inside the function.
type AlertProps = {
title: string;
message: string;
tone?: 'info' | 'success' | 'warning' | 'error';
onDismiss?: () => void;
};
function Alert({ title, message, tone = 'info', onDismiss }: AlertProps) {
return (
<aside data-tone={tone}>
<strong>{title}</strong>
<p>{message}</p>
{onDismiss && <button onClick={onDismiss}>Dismiss</button>}
</aside>
);
}
For callback props, describe the arguments and return value explicitly. A callback that accepts an identifier is different from one that receives a whole object, even if both currently call the same function.
Typing children
Use ReactNode when a component should accept ordinary JSX content, text, fragments, or conditionally rendered values. Narrow the type when the component requires a specific shape.
import type { ReactNode } from 'react';
type PanelProps = {
title: string;
children: ReactNode;
};
function Panel({ title, children }: PanelProps) {
return (
<section>
<h2>{title}</h2>
<div>{children}</div>
</section>
);
}
Do not add a children prop automatically. If a component is self-contained and should not receive nested content, leaving children out makes accidental usage visible to the compiler.
Typing React events
Choose the event type based on the element and event, not on the handler's name. Common examples include ChangeEvent<HTMLInputElement>, FormEvent<HTMLFormElement>, MouseEvent<HTMLButtonElement>, and KeyboardEvent<HTMLInputElement>.
import type { ChangeEvent, FormEvent } from 'react';
function SearchForm() {
const [query, setQuery] = useState('');
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
setQuery(event.currentTarget.value);
};
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
// Submit the validated query here.
};
return (
<form onSubmit={handleSubmit}>
<input value={query} onChange={handleChange} />
<button type="submit">Search</button>
</form>
);
}
Inline handlers are often inferred correctly, so you can start with onChange={(event) => ...}. Add an explicit event type when extracting a handler, exporting a handler utility, or documenting a component callback.
Typing refs and forwarded refs
Match the ref target to the element that receives it. Use useRef<HTMLInputElement>(null) for an input and useRef<HTMLDivElement>(null) for a div. The target should describe the DOM API the caller expects, not merely the element currently rendered by the implementation.
import { forwardRef } from 'react';
import type { InputHTMLAttributes } from 'react';
type SearchInputProps = InputHTMLAttributes<HTMLInputElement> & {
label: string;
};
const SearchInput = forwardRef<HTMLInputElement, SearchInputProps>(
function SearchInput({ label, id = 'search', ...inputProps }, ref) {
return (
<label htmlFor={id}>
{label}
<input id={id} ref={ref} {...inputProps} />
</label>
);
}
);
Use forwardRef when a component needs to expose a ref through its boundary. Keep the ref target and the supported props aligned. If the component exposes methods rather than a DOM node, define a small handle interface and expose only those methods.
Building generic React components
Generic components are useful for lists, tables, selects, and data views where the component should preserve the type of each item. The key is to require a way to turn an item into a stable key or visible representation.
type ListProps<T> = {
items: T[];
getKey: (item: T) => string;
renderItem: (item: T) => ReactNode;
};
function List<T>({ items, getKey, renderItem }: ListProps<T>) {
return (
<ul>
{items.map((item) => (
<li key={getKey(item)}>{renderItem(item)}</li>
))}
</ul>
);
}
When TypeScript has trouble parsing a generic arrow function in a TSX file, use a trailing comma in the type parameter list—<T,>—or use a function declaration as above. Let the call site infer T whenever possible instead of requiring callers to provide it manually.
What to double-check
- Public API: Are required props actually required? Are unions narrow enough to prevent unsupported states?
- Native props: If you wrap an input, button, or link, are relevant native attributes preserved with the correct element type?
- Prop collisions: Have you avoided redefining a native prop with an incompatible meaning, such as changing the expected type of
onClick? - Event targets: Are you using
currentTargetwhen you mean the element receiving the handler? The event's target may be a nested element. - Ref behavior: Does the ref point to the element or imperative handle that the component promises? Is the nullable initial state handled?
- Generic inference: Does the component preserve the item type through callbacks, or has a broad annotation erased it?
- Runtime boundaries: Types do not validate API responses, form input, or local storage at runtime. Validate external data before passing it into typed components.
- Tests: Test the component's supported usage and its interaction behavior. Type-safe fixtures can make these tests easier to maintain; see the TypeScript testing patterns guide.
Common mistakes
Using any to silence an event error. Replace it with the element-specific React event type, then inspect whether the handler belongs on the element you think it does.
Typing every component as React.FC. A plain function with an explicit props type is usually clearer and does not imply that every component accepts children. Use the style that matches your project's conventions, but keep the public contract explicit.
Overusing ComponentProps. Utility types such as ComponentPropsWithoutRef<'button'> are useful for wrappers, but they can make an API difficult to read when copied too broadly. Extend native props intentionally and add your custom fields separately.
Making a generic component too generic. If a component needs only a label and an identifier, a concrete domain type may be easier to understand than several type parameters. Generalize after you identify a repeated, stable pattern.
Confusing compile-time types with runtime safety. A prop typed as User can still receive malformed data if that data came from an unvalidated request. Keep API typing and runtime validation as separate steps; the API typing guide covers the boundary between schemas and client code.
When to revisit
Review a component's TypeScript contract whenever its inputs or responsibilities change—not only when the compiler reports an error. Revisit it when you add a ref, expose a new native attribute, change a callback's payload, introduce a loading or error state, or turn a one-off component into a shared generic component.
It is also worth checking this workflow during planned dependency or tooling updates. React type definitions, TypeScript syntax, JSX configuration, lint rules, and test utilities can change independently, so compile the component examples and run the relevant tests after an upgrade rather than assuming the old pattern still expresses the same contract.
Before merging a component API change, use this short final checklist:
- Read the props type as if you were a consumer who cannot see the implementation.
- Try the intended JSX usage and one or two invalid usages in an editor or type-check command.
- Confirm event types, ref targets, children behavior, and generic inference.
- Check runtime validation for values arriving from outside the application.
- Update nearby tests and any shared component documentation.
For related compiler diagnostics, keep the common TypeScript errors guide nearby. Strong React types are most valuable when they remain understandable at the call site, accurate at runtime boundaries, and easy to revisit as the component evolves.