Nono.MA

Add TypeScript to Next.js

JUNE 11, 2022

Here are the steps to add TypeScript to your Next.js React application.

I assume you have a Next.js React application that can run in development mode. If that's not the case, Create a Next.js app first.

# Enter the directory of your app
cd nextjs-app
# Run Next.js in development
npm run dev
# ready - started server on 0.0.0.0:3000, url: http://localhost:3000

If you can access your site at http://localhost:3000, you're good to go.

Create a tsconfig.json file

# Create an empty TypeScript configuration file
touch tsconfig.json

Simply by creating a tsconfig.json file and restarting the application, Next.js will warn us that we're trying to work with TypeScript and have to install a set of required dependencies.

# Stop the running app with `CMD + C` (or `CTRL + C` on Windows)
# Run Next.js in development once again
npm run dev

You should receive the following warning when restarting the app.

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
It looks like you're trying to use TypeScript but do not have
the required package(s) installed.

Please install typescript, @types/react, and @types/node by running:

  npm install --save-dev typescript @types/react @types/node

If you are not trying to use TypeScript, please remove the
tsconfig.json file from your package root (and any TypeScript
files in your pages directory).

Install TypeScript, React Types, and Node Types

npm install --save-dev typescript @types/react @types/node

Run your app

npm run dev
# ready - started server on 0.0.0.0:3000, url: http://localhost:3000
# We detected TypeScript in your project and created a tsconfig.json
# file for you.

Note that Next.js detected the tsconfig.json file, verified our dependencies were installed, and then populated our empty TypeScript configuration file with a boilerplate JSON object.

// tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "incremental": true,
    "esModuleInterop": true,
    "module": "esnext",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve"
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

From index.js into index.tsx

Your application is now ready to be written in TypeScript. The example we've used only has one file named index.js. Rename it to index.tsx and re-write the JavaScript code (and any new code you add to the app) in TypeScript.

Learning More

If you want to learn more, you can watch my video on How to build a Next.js app with React & TypeScript and take a look at Next.js's official TypeScript tutorial.

BlogCodeReactTypescriptNextjsJavascript