LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 4515 min read

TypeScript with Next.js

Add TypeScript to a Next.js project and use its built-in types for pages, layouts, and route parameters.

Why Add TypeScript

TypeScript catches an entire category of bugs — passing the wrong shape of data between a Server and Client Component, misspelling a params key — at build time instead of in production. Next.js has first-class TypeScript support, including its own generated types for routes.

Adding TypeScript to an Existing Project

If you didn't select TypeScript when scaffolding, add it by creating a tsconfig.json and renaming files — Next.js finishes the setup automatically the next time you run the dev server.

npm install --save-dev typescript @types/react @types/node
touch tsconfig.json
npm run dev
# Next.js detects tsconfig.json and fills it in with recommended defaults

Typing Pages and Params

// app/blog/[slug]/page.tsx
type Props = {
params: { slug: string };
searchParams: { [key: string]: string | string[] | undefined };
};
export default async function BlogPostPage({ params, searchParams }: Props) {
const post = await getPostBySlug(params.slug);
return <article>{post.title}</article>;
}

Typing Component Props

type CardProps = {
title: string;
children: React.ReactNode;
};
export default function Card({ title, children }: CardProps) {
return (
<div className="card">
<h3>{title}</h3>
{children}
</div>
);
}
Server Action Types

A Server Action's formData parameter is typed as FormData, and its return value's shape flows through to useActionState automatically — TypeScript will catch a mismatched field name at compile time.

FAQs

No — Next.js supports .js and .tsx files side by side, so you can migrate incrementally, file by file.

Type-checking runs separately from the dev server's fast bundling, so it doesn't block Fast Refresh — you'll see type errors reported alongside, not instead of, a working preview.

Summary

TypeScript integrates cleanly into Next.js, with built-in typing support for the App Router's conventions like params and searchParams. Next, you'll look at testing a Next.js application.

Next Lesson →

Testing Next.js Apps