TypeScript Integration

Learn to configure Next.js with TypeScript, and learn about customization using Babel and webpack configurations.

TypeScript configuration in Next.js

The Next.js source code is written in TypeScript and natively provides high-quality type definitions to make our developer experience even better. Configuring TypeScript as the default language for our Next.js app is very easy; we just have to create a TypeScript configuration file (tsconfig.json) inside the root of our project. If we try to run, we’ll see the following output:

It looks like you're trying to use TypeScript but do not have
the required package(s) installed.
Please install typescript and @types/react by running:
npm install --save typescript @types/react
If you are are not trying to use TypeScript, please remove
the tsconfig.json file from your package root (and any
TypeScript files in your pages directory).

As we can see, Next.js has correctly detected that we’re trying to use TypeScript and asks us to install all the required dependencies for using it as the primary language for our project. So now we just have to convert our JavaScript files to TypeScript, and we’re ready to go.

We may notice that even if we created an empty tsconfig.json file, after installing the required dependencies and rerunning the project, Next.js fills it with its default configurations. Of course, we can always customize the TypeScript options inside that file, but keep in mind that Next.js uses Babel to handle TypeScript files (via the @babel/plugin-transform-typescript), and it has some caveats, including the ...