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

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

ElementEvent type
<input>ChangeEvent<HTMLInputElement>
<form>FormEvent<HTMLFormElement>
<button>MouseEvent<HTMLButtonElement>

useRef Types

DOM ref:

tsx
const inputRef = useRef<HTMLInputElement>(null);
 
inputRef.current?.focus();

Mutable value ref (not for DOM):

tsx
const timerRef = useRef<number | null>(null);

forwardRef

Generic Components

Zustand Store Types

Router Types

tsx
import { useParams } from "react-router-dom";
 
const { slug } = useParams<{ slug: string }>();

Loader data:

tsx
const post = useLoaderData() as Post;

Prefer shared Post type in src/types/post.ts.

Type Checking Workflow

ToolRole
ViteFast dev transpile (esbuild)
tsc --noEmit or npm run buildFull type check

package.json:

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?

tsx
import type { User } from "../types/user";

vue-tsc equivalent?

tsc with jsx: react-jsx in tsconfig.app.json.

Next chapter?

Testing React Components.