React with TypeScript · Lesson 28 of 31
React with TypeScript
Most professional React codebases are written in TypeScript. Types catch wrong props, missing cases and undefined bugs as you type, and your editor autocompletes every prop and event. You need only a handful of patterns to type almost everything in a React app – this lesson covers them. Start a project with npm create vite@latest my-app -- --template react-ts.
In this lesson
- Typing props, optional props and children
useStatewith unions andnull- Event handler types
useRefand extending native element props
Typing props
type CourseCardProps = {
title: string;
lessons: number;
level?: "beginner" | "intermediate" | "advanced"; // optional, limited to three values
tags: string[];
};
function CourseCard({ title, lessons, level = "beginner", tags }: CourseCardProps) {
return (
<article>
<h3>{title}</h3>
<p>{lessons} lessons · {level} · {tags.join(", ")}</p>
</article>
);
}
export default function App() {
return (
<>
<CourseCard title="React.js" lessons={31} tags={["hooks", "router"]} />
<CourseCard title="TypeScript" lessons={17} level="intermediate" tags={["generics"]} />
</>
);
}
React.js 31 lessons · beginner · hooks, router TypeScript 17 lessons · intermediate · generics
Pass the wrong thing and the editor complains before you even run the app:
type CourseCardProps = { title: string; lessons: number; level?: "beginner" | "advanced" };
function CourseCard({ title, lessons }: CourseCardProps) {
return <h3>{title} ({lessons})</h3>;
}
export default function App() {
return (
<>
<CourseCard title="React.js" lessons="31" />
<CourseCard title="Next.js" lessons={24} level="expert" />
<CourseCard lessons={10} />
</>
);
}
main.tsx(9,36): error TS2322: Type 'string' is not assignable to type 'number'.
main.tsx(10,48): error TS2322: Type '"expert"' is not assignable to type '"advanced" | "beginner" | undefined'.
main.tsx(11,8): error TS2741: Property 'title' is missing in type '{ lessons: number; }' but required in type 'CourseCardProps'.Plain functions, not React.FC
Type the props parameter directly, as above. React.FC still works, but it adds nothing useful any more, and the React and TypeScript communities recommend plain function declarations.
Children
import type { ReactNode } from "react";
type CardProps = {
title: string;
children: ReactNode; // anything renderable: JSX, strings, numbers, arrays, null
footer?: ReactNode;
};
function Card({ title, children, footer }: CardProps) {
return (
<section>
<h2>{title}</h2>
{children}
{footer && <footer>{footer}</footer>}
</section>
);
}
export default function App() {
return (
<Card title="Streak" footer={<small>Keep going!</small>}>
<p>🔥 12 days</p>
</Card>
);
}
Streak 🔥 12 days Keep going!
useState
TypeScript infers the type from the initial value. Give it explicitly when the initial value doesn't show every possibility – null, an empty array or a union:
import { useState } from "react";
type User = { id: number; name: string };
type Status = "idle" | "saving" | "saved";
export default function App() {
const [count, setCount] = useState(0); // inferred: number
const [user, setUser] = useState<User | null>(null); // starts empty
const [tags, setTags] = useState<string[]>([]); // [] alone would be never[]
const [status, setStatus] = useState<Status>("idle");
return (
<div>
<p>{user ? `Hi, ${user.name}` : "Not logged in"} · visits: {count} · {tags.join(", ") || "no tags"} · {status}</p>
<button onClick={() => { setUser({ id: 1, name: "Asha" }); setCount((c) => c + 1); }}>Log in</button>
<button onClick={() => { setTags((t) => [...t, "react"]); setStatus("saved"); }}>Tag</button>
</div>
);
}
Not logged in · visits: 0 · no tags · idle [Log in] [Tag] › click “Log in” Hi, Asha · visits: 1 · no tags · idle [Log in] [Tag] › click “Tag” Hi, Asha · visits: 1 · react · saved [Log in] [Tag]
With User | null, TypeScript forces you to check user before reading user.name – the classic "cannot read properties of null" crash is caught at compile time.
Events
import { useState, type ChangeEvent, type FormEvent, type KeyboardEvent } from "react";
export default function App() {
const [email, setEmail] = useState("");
const [log, setLog] = useState<string[]>([]);
function handleChange(e: ChangeEvent<HTMLInputElement>) {
setEmail(e.target.value); // e.target is typed as HTMLInputElement
}
function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {
if (e.key === "Escape") setEmail("");
}
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
setLog((l) => [...l, `subscribed ${email}`]);
}
return (
<form onSubmit={handleSubmit}>
<input aria-label="Email" value={email} onChange={handleChange} onKeyDown={handleKeyDown} />
<button>Subscribe</button>
{log.map((line) => <p key={line}>{line}</p>)}
</form>
);
}
[] [Subscribe] › type “asha@example.com” into Email [asha@example.com] [Subscribe] › click “Subscribe” [asha@example.com] [Subscribe] subscribed asha@example.com
Don't memorise these names: write the handler inline once (onChange={(e) => …}), hover over e in your editor, and copy the type it shows.
| Prop | Event type |
|---|---|
onChange on an input | ChangeEvent<HTMLInputElement> |
onSubmit | FormEvent<HTMLFormElement> |
onClick | MouseEvent<HTMLButtonElement> |
onKeyDown | KeyboardEvent<HTMLInputElement> |
| a callback prop | describe it: onRate: (stars: number) => void |
useRef
import { useRef, useState } from "react";
export default function App() {
const inputRef = useRef<HTMLInputElement>(null); // a DOM ref: starts as null
const timerRef = useRef<number | null>(null); // a mutable value
const [saved, setSaved] = useState(false);
function handleSave() {
inputRef.current?.focus(); // ?. because it may be null
if (timerRef.current !== null) clearTimeout(timerRef.current);
timerRef.current = window.setTimeout(() => setSaved(false), 1000);
setSaved(true);
}
return (
<div>
<input ref={inputRef} aria-label="Title" defaultValue="My notes" />
<button onClick={handleSave}>Save</button>
{saved && <p>Saved ✔</p>}
</div>
);
}
[My notes] [Save] › click “Save” [My notes] [Save] Saved ✔
Accepting every native prop
A custom Button should accept everything a real <button> does – type, disabled, aria-*, onClick – plus your own props:
import type { ComponentProps } from "react";
type ButtonProps = ComponentProps<"button"> & {
variant?: "primary" | "ghost";
};
function Button({ variant = "primary", className = "", ...rest }: ButtonProps) {
return <button className={`btn btn--${variant} ${className}`.trim()} {...rest} />;
}
export default function App() {
return (
<>
<Button type="submit" disabled>Saving…</Button>
<Button variant="ghost" aria-label="Bookmark" onClick={(e) => console.log(e.currentTarget.tagName)}>☆</Button>
</>
);
}
[Saving… (disabled)] [☆] › click “Bookmark” [Saving… (disabled)] [☆] console: BUTTON
ComponentProps<"button"> includes the ref prop in React 19, so refs pass through ...rest too.
Practice
Try it yourself
Type a
Ratingcomponent withvalue: numberandonChange: (value: number) => void, and use it with state.Show solution
import { useState } from "react"; type RatingProps = { value: number; max?: number; onChange: (value: number) => void }; function Rating({ value, max = 5, onChange }: RatingProps) { return ( <div> {Array.from({ length: max }, (_, i) => i + 1).map((n) => ( <button key={n} aria-label={`${n} stars`} onClick={() => onChange(n)}>{n <= value ? "★" : "☆"}</button> ))} </div> ); } export default function App() { const [stars, setStars] = useState(0); return ( <> <Rating value={stars} onChange={setStars} /> <p>{stars}/5</p> </> ); }[☆] [☆] [☆] [☆] [☆] 0/5 › click “4 stars” [★] [★] [★] [★] [☆] 4/5
Quick check
Which type do you use for a children prop?
ReactNode.
Why write useState<string[]>([])?
An empty array alone is inferred as never[], so you couldn't add strings.
How do you type a ref to an input?
useRef<HTMLInputElement>(null), then use ref.current?.….
Summary
- Type props with a type or interface on the parameter; use ReactNode for children.
- Give useState a type for null, empty arrays and unions; let it infer simple values.
- Use React's event types and useRef<Element>(null); extend ComponentProps<"tag"> for wrappers.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.