React with TypeScript: Typing Props, State and Events
Master React with TypeScript: type components, props, state, event handlers, and custom hooks with compile-time type safety using the react-ts template.
What you will learn
In JavaScript, misspelling a prop name (like writing title instead of headline) or passing an object instead of an array fails silently until the app runs in the browser and throws a runtime exception. In large professional teams, catching these mistakes before running the code saves hours of debugging.
TypeScript adds static types to JavaScript, providing autocomplete, instant inline documentation, and build-time verification.
In Build Along: Notes CRUD App, you built a full interactive CRUD application using vanilla JavaScript. In this lesson, you will learn how to make that codebase rock-solid with TypeScript static types:
- How to set up a Vite React app with the
react-tstemplate. - How to define clean TypeScript types and interfaces for component props (including children and optional props).
- How TypeScript infers and types
useState,useReducer, anduseRef. - How to correctly type browser events (
onClick,onChange,onSubmit). - How to type custom hooks and reusable generic components safely.
Creating a Vite React TypeScript Project
To create a new React app with TypeScript support out of the box:
npm create vite@latest my-react-app -- --template react-ts
cd my-react-app
npm install
npm run dev
Notice the file extensions:
- Files with JSX use
.tsx(e.g.App.tsx,Button.tsx). - Pure utility or logic files use
.ts(e.g.api.ts,types.ts).
Typing Component Props
In TypeScript, you describe the shape of your props using an interface or type:
// UserCard.tsx
interface UserCardProps {
name: string;
age: number;
email: string;
role?: "admin" | "editor" | "viewer"; // Optional union type
onSelect?: (userId: string) => void; // Callback function
}
export function UserCard({ name, age, email, role = "viewer", onSelect }: UserCardProps) {
return (
<div className={`user-card role-${role}`}>
<h3>{name} ({age})</h3>
<p>{email}</p>
{onSelect && (
<button onClick={() => onSelect(email)}>Select Profile</button>
)}
</div>
);
}
If another developer attempts to write <UserCard name="Alex" age="twenty" />, their IDE immediately highlights age in red with:
Type 'string' is not assignable to type 'number'.
Typing children
When building container or layout wrappers, type children with React.ReactNode:
import type { ReactNode } from 'react';
interface CardWrapperProps {
title: string;
children: ReactNode; // Accepts JSX, strings, numbers, fragments, or null
}
export function CardWrapper({ title, children }: CardWrapperProps) {
return (
<div className="card">
<header className="card-header">
<h2>{title}</h2>
</header>
<div className="card-body">
{children}
</div>
</div>
);
}
Typing Hooks
TypeScript’s type inference handles most React hooks automatically, but some require explicit generic types.
1. useState
When initializing with primitive values, TypeScript infers the type automatically:
const [count, setCount] = useState(0); // Inferred as number
const [name, setName] = useState(""); // Inferred as string
When initializing with null before data arrives from an API:
interface User {
id: string;
username: string;
}
// Explicit generic parameter: User or null
const [user, setUser] = useState<User | null>(null);
// Later in your JSX:
// user.username TS Error: 'user' is possibly 'null'
// user?.username Safe navigation
2. useRef
When referencing DOM elements, provide the specific HTML element interface and initialize with null:
import { useRef } from 'react';
function SearchInput() {
// Specifically types the ref as an HTMLInputElement
const inputRef = useRef<HTMLInputElement>(null);
function focusField() {
inputRef.current?.focus();
}
return <input ref={inputRef} type="search" />;
}
3. useReducer
Combine TypeScript discriminated unions with reducers for unbeatable state safety:
interface State {
count: number;
}
// Discriminated union of allowed actions
type Action =
| { type: "increment" }
| { type: "decrement" }
| { type: "reset"; payload: number };
function counterReducer(state: State, action: Action): State {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
case "reset":
return { count: action.payload }; // TypeScript knows payload exists here!
default:
return state;
}
}
If you accidentally dispatch { type: "unknown" }, TypeScript flags it at compile time.
Typing Form and Mouse Events
When attaching inline handlers, TypeScript automatically knows what event is:
<input onChange={(e) => console.log(e.target.value)} />
When extracting the handler to a named function, annotate the event with React’s event types from 'react':
import type { ChangeEvent, FormEvent, MouseEvent } from 'react';
export function ContactForm() {
function handleTextChange(event: ChangeEvent<HTMLInputElement>) {
console.log(event.target.value);
}
function handleButtonClick(event: MouseEvent<HTMLButtonElement>) {
console.log("Clicked at coordinates:", event.clientX, event.clientY);
}
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
console.log("Form submitted safely");
}
return (
<form onSubmit={handleSubmit}>
<input type="text" onChange={handleTextChange} />
<button type="submit" onClick={handleButtonClick}>Send</button>
</form>
);
}
Quick Event Reference:
ChangeEvent<HTMLInputElement>: Text inputs, checkboxes, radios.ChangeEvent<HTMLSelectElement>:<select>dropdowns.ChangeEvent<HTMLTextAreaElement>:<textarea>multiline text.FormEvent<HTMLFormElement>: Form submit events.MouseEvent<HTMLButtonElement>: Button clicks.KeyboardEvent<HTMLInputElement>: Keydown and keyup events.
Typing Custom Hooks
When a custom hook returns an array tuple (like useState), tell TypeScript it is a constant tuple using as const:
import { useState } from 'react';
export function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = () => setValue((v) => !v);
// 'as const' ensures TS infers [boolean, () => void] instead of (boolean | () => void)[]
return [value, toggle] as const;
}
Common mistakes
1. Using any whenever a type error occurs
Using const [data, setData] = useState<any>(null) disables TypeScript’s safety features entirely. Define real interfaces for your API models.
2. Typing children as JSX.Element
JSX.Element only accepts a single JSX tag. It rejects plain strings, numbers, arrays, and null. Always prefer React.ReactNode for children.
3. Forgetting the HTML prefix on event targets
Writing ChangeEvent<InputElement> is a syntax error. Native DOM element types are prefixed with HTML: HTMLInputElement, HTMLDivElement, HTMLButtonElement.
Practice
- Create a
Buttoncomponent in.tsxthat acceptsvariant?: 'primary' | 'secondary' | 'danger',disabled?: boolean, andonClick: () => void. - Build an
interface TodoItemwithid: number,title: string, andcompleted: boolean. Build aTodoListcomponent that acceptsitems: TodoItem[]. - Create a custom input component with an
inputRef = useRef<HTMLInputElement>(null). Add a button that selects all text usinginputRef.current?.select(). - Type a login form with
ChangeEvent<HTMLInputElement>on email/password fields andFormEvent<HTMLFormElement>on submit. - Create a generic list component
function List<T>({ items, renderItem }: ListProps<T>)that can render arrays of any type. - Run
npm run buildin your TypeScript project and verify that the TypeScript compiler (tsc) catches type errors before generating the bundle.
Recap
- TypeScript catches bugs at build time, provides auto-completion, and serves as living documentation.
- Use
interfaceortypeto describe component props and callback signatures. - Type
childrenusingReact.ReactNode. - Generic hooks like
useState<User | null>(null)anduseRef<HTMLInputElement>(null)ensure safe DOM and state operations. - Annotate event handlers with
ChangeEvent<HTMLInputElement>orFormEvent<HTMLFormElement>. - In the next lesson, you will learn how to write automated component tests with Vitest and React Testing Library!
Frequently asked questions
Should I use interface or type for React props?
Both work well. In general, interface is preferred for component props because it produces clean error messages and supports declaration merging. type is preferred for unions (e.g. 'small' | 'large') and tuple returns.
Do I need to import React in every .tsx file with TypeScript?
No. Modern TypeScript with "jsx": "react-jsx" in tsconfig.json uses the automatic JSX runtime, so import React from 'react' is not required unless you are using React namespace members.
How do I type HTML attributes like className and style on custom components?
Extend React’s built-in component prop types: interface MyBtnProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { customVariant?: string; }. Your button will automatically inherit className, id, disabled, and standard HTML attributes.
Does TypeScript slow down my production app in the browser?
Zero slowdown. TypeScript types are completely stripped away during the Vite build process. The browser runs 100% clean, standard JavaScript.
Can I migrate an existing JavaScript React app to TypeScript gradually?
Yes! TypeScript allows you to rename files one by one from .jsx to .tsx. You can type your core components first and migrate secondary pages over time.
See also: React Project Structure, React Props, Handling Events in React