DEV Community

Cover image for Add Typescript to your Next.js project
Bhanu Teja Pachipulusu
Bhanu Teja Pachipulusu

Posted on • Updated on • Originally published at blog.bhanuteja.dev

Add Typescript to your Next.js project

It's very easy to add typescript to a Next.js project. In this post, I will list out steps on how to do so.

First, let's create a new Nextjs project my-ts-app

# Create a directory with name `my-ts-app`
mkdir my-ts-app

# Change directory to `my-ts-app`
cd my-ts-app

# Initialize the directory as an npm project
npm init -y

# Install `next`, `react` and `react-dom` as dependencies
npm install next react react-dom

# Create a directory with name `pages`
mkdir pages

# Create a file with name `index.tsx` inside `pages` directory
touch pages/index.tsx
Enter fullscreen mode Exit fullscreen mode

File Structure
Alt Text


Your package.json file

Alt Text

Add the following scripts to your package.json

"scripts": {
  "dev": "next dev",
  "build": "next build",
  "start": "next start"
}
Enter fullscreen mode Exit fullscreen mode

Alt Text


Add the following to your pages/index.tsx file

// pages/index.tsx

function HomePage() {
  return <div>Welcome to Next.js!</div>
}

export default HomePage
Enter fullscreen mode Exit fullscreen mode

Now, let's add typescript to the project.

# Create an empty `tsconfig.json` file
touch tsconfig.json

# Add `typescript`, `@types/react` and `@types/node` as devDependencies
npm install --save-dev typescript @types/react @types/node
Enter fullscreen mode Exit fullscreen mode

That's it. Next time you run npm run dev, tsconfig.json will be auto-populated with recommended typescript config for Next.js.

Alt Text

Alt Text

Open localhost:3000 in your browser

Alt Text


Now, you can add types to your project as you normally would to any typescript project.

If you like what you read here, then chances are that you will also like my tweets. Head over to my twitter profile at @pbteja1998

ko-fi

Top comments (0)