1. Project Setup
To start a React project with TypeScript, use the official template:
Using Create React App
npx create-react-app my-app --template typescript
Using Vite
npm create vite@latest my-app -- --template react-ts
This sets up a TypeScript-ready React project with all necessary configurations.
2. Typing Props
Props can be typed using interfaces or type aliases.
Using Interface
interface GreetingProps {
name: string;
age?: number; // optional prop
}
const Greeting: React.FC<GreetingProps> = ({ name, age }) => {
return (
<div>
Hello, {name}! {age && `You are ${age} years old.`}
</div>
);
};
Using Type Alias
type ButtonProps = {
label: string;
onClick: () => void;
};
const Button: React.FC<ButtonProps> = ({ label, onClick }) => (
<button onClick={onClick}>{label}</button>
);
Typing props ensures components receive valid data and improves code readability.
3. Typing State
State can be typed using generics with useState.
Basic Example
import { useState } from "react";
const Counter: React.FC = () => {
const [count, setCount] = useState<number>(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
Complex State Example
interface User {
id: number;
name: string;
}
const [user, setUser] = useState<User | null>(null);
Typing state improves type safety and prevents runtime errors when updating values.
4. Event Handling
Events in React can be typed to ensure type-safe interactions.
Mouse Event
const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
console.log("Button clicked", event);
};
Change Event
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
console.log("Input value:", event.target.value);
};
Form Event
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
console.log("Form submitted");
};
Typing events ensures that you access the correct properties for each element and prevents errors.
Conclusion
Using TypeScript with React provides type safety for props, state, and events. Proper typing improves code maintainability, enhances IDE support, and reduces runtime errors, enabling developers to build robust and scalable React applications.