You are viewing a free preview of this lesson.
Subscribe to unlock all 12 lessons in this course and every other course on LearningBro.
React and TypeScript are a natural pairing. TypeScript catches prop mismatches, state errors, and event handler mistakes at compile time rather than at runtime. This lesson covers how to type components, props, state, hooks, events, context, and refs in a React application.
Create a new TypeScript React project with Vite or Next.js:
// Vite:
// npm create vite@latest my-app -- --template react-ts
// Next.js:
// npx create-next-app@latest my-app --typescript
React's type definitions are provided by @types/react and @types/react-dom.
The most common pattern is to type the props inline or via an interface:
interface GreetingProps {
name: string;
age?: number;
}
function Greeting({ name, age }: GreetingProps) {
return (
<div>
<h1>Hello, {name}!</h1>
{age !== undefined && <p>Age: {age}</p>}
</div>
);
}
// Usage:
// <Greeting name="Alice" />
// <Greeting name="Bob" age={30} />
Type the children prop explicitly using React.ReactNode:
interface CardProps {
title: string;
children: React.ReactNode;
}
function Card({ title, children }: CardProps) {
return (
<div className="card">
<h2>{title}</h2>
<div className="card-body">{children}</div>
</div>
);
}
Subscribe to continue reading
Get full access to this lesson and all 12 lessons in this course.