Here are some Next.js specific types you can use.
For getStaticProps
, getStaticPaths
, and getServerSideProps
, you can use the GetStaticProps
, GetStaticPaths
, and GetServerSideProps
types respectively:
import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next' export const getStaticProps: GetStaticProps = async context => { // ... } export const getStaticPaths: GetStaticPaths = async () => { // ... } export const getServerSideProps: GetServerSideProps = async context => { // ... }
The following is an example of how to use the built-in types for API routes:
import { NextApiRequest, NextApiResponse } from 'next' export default (req: NextApiRequest, res: NextApiResponse) => { // ... }
App
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
To convert the blog app we created in the basics lessons into TypeScript, update the following files:
components/date.js
: Update to date.tsx
using this codecomponents/layout.js
: Update to layout.tsx
using this codelib/posts.js
: Update to posts.ts
using this codepages/posts/[id].js
: Update to [id].tsx
using this codepages/index.js
: Update to index.tsx
using this codepages/_app.js
: Update to _app.tsx
using this codepages/api/hello.js
: Update to hello.ts
using this codeAlso, since remark-html
doesn’t have type definitions within the package or in DefinitelyTyped, create a top-level global.d.ts
file to add a type declaration.
declare module 'remark-html' { const html: any export default html }
That’s it! Your app is now powered by TypeScript.
To learn more about using Next.js in TypeScript, take a look at our TypeScript documentation.