Type Script
Type Script
Version History
create-next-app support
You can create a TypeScript project with create-next-app using the --ts, --typescript flag
like so:
Existing projects
To get started in an existing project, create an empty tsconfig.json file in the root
folder:
touch tsconfig.json
Next.js will automatically configure this file with default values. Providing your
own tsconfig.json with custom compiler options is also supported.
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:
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 at the root of your project. This file ensures
Next.js types are picked up by the TypeScript compiler. You should not remove it or
edit it as it can change at any time. This file should not be committed and should be
ignored by version control (e.g. inside your .gitignore file).
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.
API Routes
The following is an example of how to use the built-in types for API routes:
type Data = {
name: string
}
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:
import type { AppProps } from 'next/app'
You can learn more about this feature on the Module Path aliases documentation.
// @ts-check
/**
* @type {import('next').NextConfig}
**/
const nextConfig = {
/* config options here */
}
module.exports = nextConfig
If you'd like Next.js to dangerously produce production code even when your
application has errors, you can disable the built-in type checking step.
If disabled, be sure you are running type checks as part of your build or deploy
process, otherwise this can be very dangerous.
module.exports = {
typescript: {
// !! WARN !!
// Dangerously allow production builds to successfully complete
even if
// your project has type errors.
// !! WARN !!
ignoreBuildErrors: true,
},
}
ESLintEnvironment Variables