TypeScript with React
TypeScript with React: Typing Props, State, and Events
TypeScript with React (.tsx files) catches missing component props, misspelled state fields, and invalid event handler signatures right in your editor. Instead of guessing what props a shared button or modal expects, hovering over <Button /> shows every required and optional prop instantly.
Enable "jsx": "react-jsx" in tsconfig.json and install @types/react and @types/react-dom matching your React major version.
Typing Component Props and Events
Define a clear interface or type for each component's props, and use React.ChangeEvent or React.FormEvent for browser inputs and forms.
import { useState, type ChangeEvent, type ReactNode } from "react";
interface SearchCardProps {
title: string;
initialQuery?: string;
onSearch: (query: string) => void;
children?: ReactNode;
}
export function SearchCard({ title, initialQuery = "", onSearch, children }: SearchCardProps) {
const [query, setQuery] = useState(initialQuery); // Inferred as string
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
setQuery(e.target.value);
};
return (
<section>
<h2>{title}</h2>
<input value={query} onChange={handleChange} />
<button onClick={() => onSearch(query)}>Search</button>
{children}
</section>
);
}
Typing useState and useRef
When initial state is empty or nullable, pass a generic parameter: const [user, setUser] = useState<User | null>(null);. For DOM element refs, initialize with null: const inputRef = useRef<HTMLInputElement>(null);.
Common Mistakes to Avoid
- Using
React.FCeverywhere unnecessarily: Plain function declarations (function Card(props: CardProps)) handle generics better and avoid hidden implicitchildrenbugs from older@types/react. - Typing
childrenasJSX.Elementinstead ofReact.ReactNode:ReactNodeproperly allows strings, numbers, arrays, fragments, andnull. - Calling
useRef<HTMLInputElement>()withoutnull: In React 18+, omittingnullcreates a mutable ref instead of a read-only DOM ref.
Frequently Asked Questions
What is the difference between .ts and .tsx files?
.tsx files allow JSX markup tags (<div>), while .ts files forbid JSX and are used for hooks, API clients, utilities, and types.
How do I accept all native <button> HTML attributes on a custom Button component?
Extend React.ComponentPropsWithoutRef<"button"> (or React.ButtonHTMLAttributes<HTMLButtonElement>) and spread ...rest onto <button>.
Why does setItems([...items, newItem]) complain about never[]?
useState([]) with no type infers never[]; write useState<string[]>([]) or useState<Item[]>([]) instead.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.