Search code examples
typescriptdefinitelytypednext.js

Using getInitialProps in Next.js with TypeScript


From the documentation, Next.js 5.0 announcement and various articles around on the internet it seems like Next.js supports TypeScript well and many people are using it.

But these threads suggest that getInitialProps, which is vital to Next.js apps, doesn't work:

How can I fix it? In both class and functional components, when I do ComponentName.getInitialProps = async function() {...} I get the following error:

[ts] Property 'getInitialProps' does not exist on type '({ data }: { data: any; }) => Element'.

Solution

  • 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
    }