TypeScript support
Published at July 9, 2020
5 min read • Edit this post

TypeScript

Examples

Next.js provides an integrated TypeScript experience out of the box, similar to an IDE.

create-next-app support

You can create a TypeScript project with create-next-app using the --ts, --typescript flag like so:

1npx create-next-app@latest --ts
2# or
3yarn create next-app --typescript

Existing projects

To get started in an existing project, create an empty tsconfig.json file in the root folder:

BASH
1touch tsconfig.json

Next.js will automatically configure this file with default values. Providing your own tsconfig.json with custom compiler options is also supported.

You can also provide a relative path to a tsconfig.json file by setting typescript.tsconfigPath prop inside your next.config.js file.

Starting in v12.0.0, Next.js uses SWC by default to compile TypeScript and TSX for faster builds.

Next.js will use Babel to handle TypeScript if .babelrc is present. This has some caveats and some compiler options are handled differently.

Then, run next (normally npm run dev or yarn dev) and Next.js will guide you through the installation of the required packages to finish the setup:

BASH
1npm run dev
2
3# You'll see instructions like these:
4#
5# Please install TypeScript, @types/react, and @types/node by running:
6#
7# yarn add --dev typescript @types/react @types/node
8#
9# ...

You're now ready to start converting files from .js to .tsx and leveraging the benefits of TypeScript!

A file named next-env.d.ts will be created in the root of your project. This file ensures Next.js types are picked up by the TypeScript compiler. You cannot remove it or edit it as it can change at any time.

TypeScript strict mode is turned off by default. When you feel comfortable with TypeScript, it's recommended to turn it on in your tsconfig.json.

Instead of editing next-env.d.ts, you can include additional types by adding a new file e.g. additional.d.ts and then referencing it in the include array in your tsconfig.json.

By default, Next.js will do type checking as part of next build. We recommend using code editor type checking during development.

If you want to silence the error reports, refer to the documentation for Ignoring TypeScript errors.

Static Generation and Server-side Rendering

For getStaticProps, getStaticPaths, and getServerSideProps, you can use the GetStaticProps, GetStaticPaths, and GetServerSideProps types respectively:

TS
1import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'
2
3export const getStaticProps: GetStaticProps = async (context) => {
4 // ...
5}
6
7export const getStaticPaths: GetStaticPaths = async () => {
8 // ...
9}
10
11export const getServerSideProps: GetServerSideProps = async (context) => {
12 // ...
13}

If you're using getInitialProps, you can follow the directions on this page.

API Routes

The following is an example of how to use the built-in types for API routes:

TS
1import type { NextApiRequest, NextApiResponse } from 'next'
2
3export default (req: NextApiRequest, res: NextApiResponse) => {
4 res.status(200).json({ name: 'John Doe' })
5}

You can also type the response data:

TS
1import type { NextApiRequest, NextApiResponse } from 'next'
2
3type Data = {
4 name: string
5}
6
7export default (req: NextApiRequest, res: NextApiResponse<Data>) => {
8 res.status(200).json({ name: 'John Doe' })
9}

Custom App

If you have a custom App, you can use the built-in type AppProps and change file name to ./pages/_app.tsx like so:

TS
1// import App from "next/app";
2import type { AppProps /*, AppContext */ } from 'next/app'
3
4function MyApp({ Component, pageProps }: AppProps) {
5 return <Component {...pageProps} />
6}
7
8// Only uncomment this method if you have blocking data requirements for
9// every single page in your application. This disables the ability to
10// perform automatic static optimization, causing every page in your app to
11// be server-side rendered.
12//
13// MyApp.getInitialProps = async (appContext: AppContext) => {
14// // calls page's `getInitialProps` and fills `appProps.pageProps`
15// const appProps = await App.getInitialProps(appContext);
16
17// return { ...appProps }
18// }
19
20export default MyApp

Path aliases and baseUrl

Next.js automatically supports the tsconfig.json "paths" and "baseUrl" options.

You can learn more about this feature on the Module Path aliases documentation.

Type checking next.config.js

The next.config.js file must be a JavaScript file as it does not get parsed by Babel or TypeScript, however you can add some type checking in your IDE using JSDoc as below:

JS
1// @ts-check
2
3/**
4 * @type {import('next').NextConfig}
5 **/
6const nextConfig = {
7 /* config options here */
8}
9
10module.exports = nextConfig

Incremental type checking

Since v10.2.1 Next.js supports incremental type checking when enabled in your tsconfig.json, this can help speed up type checking in larger applications.

It is highly recommended to be on at least v4.3.2 of TypeScript to experience the best performance when leveraging this feature.

© 2022 Nam Hoang Le. All Rights Reserved. Made with 🔥 passion, a ⌨️ keyboard and Next.js
githublinkedinmailto