TypeScript With React
Introduction
TypeScript catches prop typos, wrong event handlers, and API shape mistakes before runtime. React + .tsx files use typed props, hooks, refs, and events—checked with tsc alongside Vite. This chapter focuses on React-specific patterns, not re-teaching TypeScript fundamentals.
Prerequisites
- TypeScript basics
- Composition, Props, and Lifting State
- Environment and Create React Project with TypeScript
Typed Component Props
Prefer explicit type or interface on the function—avoid React.FC for new code (children typing changed over time).
Compare Vue defineProps.
Children and HTML Attributes
Extend native element props:
useState and useReducer Types
Event Types
| Element | Event type |
|---|---|
<input> | ChangeEvent<HTMLInputElement> |
<form> | FormEvent<HTMLFormElement> |
<button> | MouseEvent<HTMLButtonElement> |
useRef Types
DOM ref:
const inputRef = useRef<HTMLInputElement>(null);
inputRef.current?.focus();Mutable value ref (not for DOM):
const timerRef = useRef<number | null>(null);forwardRef
Generic Components
Zustand Store Types
Router Types
import { useParams } from "react-router-dom";
const { slug } = useParams<{ slug: string }>();Loader data:
const post = useLoaderData() as Post;Prefer shared Post type in src/types/post.ts.
Type Checking Workflow
| Tool | Role |
|---|---|
| Vite | Fast dev transpile (esbuild) |
tsc --noEmit or npm run build | Full type check |
package.json:
"type-check": "tsc --noEmit"Run type-check in CI before deploy—Build chapter.
FAQ
React.FC still?
Annotate props on the function directly—clearer for children optional cases.
any in quick prototypes?
Replace with unknown + narrowing for API JSON.
Type import only?
import type { User } from "../types/user";vue-tsc equivalent?
tsc with jsx: react-jsx in tsconfig.app.json.