Using NextJS with TypeScript
Create an empty tsconfig.json file in the root of your project and add dependencies:
# If you’re using npm npm install --save-dev typescript @types/react @types/node # If you’re using Yarn yarn add --dev typescript @types/react @types/node
Now run yarn dev to start the server and Next.js will:
- Populate the
tsconfig.jsonfile for you. You may customize this file. - Create the
next-env.d.tsfile, which ensures Next.js types are picked up by the TypeScript compiler. You should not touch this file.
Here is how you use the types:
import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'
export const getStaticProps: GetStaticProps = async context => {
// ...
}
export const getStaticPaths: GetStaticPaths = async () => {
// ...
}
export const getServerSideProps: GetServerSideProps = async context => {
// ...
}
This is how you use API Routes with TypeScript:
import { NextApiRequest, NextApiResponse } from 'next'
export default (req: NextApiRequest, res: NextApiResponse) => {
// ...
}
You can convert pages/_app.js into pages/_app.tsx and use the built-in type AppProps, like so:
import { AppProps } from 'next/app'
function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
export default App