28. Next Steps: Exploring TypeScript with React
Level: AdvancedDuration: 18m
Why Use TypeScript with React?
TypeScript helps catch bugs earlier by enforcing types during development. In React, it improves component reliability, reduces runtime errors, and makes your code easier to understand and maintain.
Setting Up React with TypeScript
bash
npm create vite@latest my-app --template react-tsWe use Vite because it’s fast, modern, and supports TypeScript out of the box.
Typing Props in Functional Components
tsx
type ButtonProps = {
label: string;
disabled?: boolean;
};
export default function Button({ label, disabled = false }: ButtonProps) {
return <button disabled={disabled}>{label}</button>;
}Optional props are marked with a question mark (?). TypeScript enforces that components receive the correct prop types.
Typing useState and useRef
tsx
const [count, setCount] = useState<number>(0);
const inputRef = useRef<HTMLInputElement>(null);Typing hooks ensures consistency and prevents passing invalid data into your state or refs.
Typing API Data
tsx
interface Post {
id: number;
title: string;
body: string;
}
axios.get<Post[]>("/api/posts").then(response => {
console.log(response.data);
});Typing your data responses avoids undefined errors and improves code readability.
| Concept | Example | Benefit |
|---|---|---|
| Props typing | type Props {} | Prevents wrong props |
| State typing | useState<number> | Ensures valid state |
| API typing | axios.get<Post[]> | Safe API responses |
Mini Project Step
Convert your existing React Todo component to TypeScript by typing props, state, and functions. Add an interface for todo items and enforce stricter code quality.