TypeScript Integration
Type-safe routes, API routes, server components, and type generation.
Overview
TypeScript provides type safety across Next.js applications.
Key Concepts
- Type-Safe Routes — Typed params and search params
- API Route Types — Typed request/response
- Server Component Types — Typed async components
- Type Generation — Auto-generate types from APIs
- Strict Mode — Enable strict TypeScript checking
Code Examples
// app/blog/[slug]/page.tsx
type PageProps = {
params: { slug: string };
searchParams: { [key: string]: string | string[] | undefined };
};
export default async function BlogPost({ params, searchParams }: PageProps) {
const post = await getPost(params.slug);
return <article>{post.content}</article>;
}
// app/api/products/route.ts
import { NextRequest, NextResponse } from 'next/server';
type Product = {
id: string;
name: string;
price: number;
};
export async function GET(request: NextRequest): Promise<NextResponse<Product[]>> {
const products = await db.products.findMany();
return NextResponse.json(products);
}
export async function POST(request: NextRequest): Promise<NextResponse<Product>> {
const body = await request.json();
const product = await db.products.create({ data: body });
return NextResponse.json(product, { status: 201 });
}
// Type-safe server actions
'use server';
import { z } from 'zod';
const CreatePostSchema = z.object({
title: z.string().min(1).max(200),
content: z.string().min(1)
});
type CreatePostInput = z.infer<typeof CreatePostSchema>;
export async function createPost(input: CreatePostInput) {
const result = CreatePostSchema.safeParse(input);
if (!result.success) {
return { error: result.error.flatten().fieldErrors };
}
const post = await db.posts.create({ data: result.data });
return { data: post };
}
Practice
Add TypeScript to a Next.js project with type-safe routes and API.