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'.
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
}