Edit 2021/04/23: My answer below is also out of date
Please see the Next.js docs for the current recommendation for typing data fetching methods using new types and named exports.
tl;dr:
import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next' export const getStaticProps: GetStaticProps = async (context) => { // ... } export const getStaticPaths: GetStaticPaths = async () => { // ... } export const getServerSideProps: GetServerSideProps = async (context) => { // ... }
Out of date (but functional) answer:
The above answers are out of date since Next.js now officially supports TypeScript (announcement here)
Part of this release is better TypeScript types, with much of Next.js being written in TypeScript itself. This means that the @types/next
package will be deprecated in favour of the official Next.js typings.
Instead, you should import the NextPage
type and assign that to your component. You can also type getInitialProps
using the NextPageContext
type.
import { NextPage, NextPageContext } from 'next'; const MyComponent: NextPage<MyPropsInterface> = props => ( // ... ) interface Context extends NextPageContext { // any modifications to the default context, e.g. query types } MyComponent.getInitialProps = async (ctx: Context) => { // ... return props }