0
0
NextJSframework~5 mins

TypeScript support in Next.js

Choose your learning style9 modes available
Introduction

TypeScript helps catch mistakes early by checking your code. Next.js supports TypeScript to make building web apps safer and easier.

You want to avoid bugs by checking your code as you write.
You are building a web app with Next.js and want better code hints.
You want to use modern JavaScript plus type safety.
You want your team to understand code better with clear types.
You want to catch errors before running your app.
Syntax
NextJS
1. Rename your files from .js to .tsx for components or .ts for other files.
2. Add a tsconfig.json file to configure TypeScript.
3. Next.js will automatically detect TypeScript and install needed packages.
4. Use types for props and state in your components.

Example component:

import React from 'react';

type Props = { message: string };

export default function Hello({ message }: Props) {
  return <h1>{message}</h1>;
}

Next.js auto-creates a default tsconfig.json if you don't have one.

Use .tsx for React components to allow JSX syntax with TypeScript.

Examples
Simple typed component with a number prop.
NextJS
import React from 'react';

type Props = { count: number };

export default function Counter({ count }: Props) {
  return <p>Count is {count}</p>;
}
Using an interface to type a function return value.
NextJS
interface User {
  id: number;
  name: string;
}

export function getUser(): User {
  return { id: 1, name: 'Alice' };
}
Basic component without props, still using TypeScript file.
NextJS
export default function Page() {
  return <div>Hello from TypeScript in Next.js!</div>;
}
Sample Program

This is a simple Next.js component using TypeScript. It takes a name prop typed as a string and displays a greeting.

NextJS
import React from 'react';

type GreetingProps = {
  name: string;
};

export default function Greeting({ name }: GreetingProps) {
  return <h2>Hello, {name}!</h2>;
}
OutputSuccess
Important Notes

TypeScript helps you find errors before running your app.

Next.js automatically reloads when you change TypeScript files.

Use the Next.js docs for advanced TypeScript features like API routes and getStaticProps.

Summary

Next.js supports TypeScript out of the box for safer code.

Rename files to .ts or .tsx and add types for props and data.

Next.js auto-configures TypeScript and reloads on changes.