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'.
Make sure the returned object from getInitialProps is a plain Object and not using Date , Map or Set . For the initial page load, getInitialProps will run on the server only. getInitialProps will then run on the client when navigating to a different route via the next/link component or by using next/router .
Next. js provides an integrated TypeScript experience, including zero-configuration set up and built-in types for Pages, APIs, and more.
on Sep 21, 2020. getInitialProps is not deprecated. But we do not recommend its usage over getStaticProps or getServerSideProps . That's doesn't mean you can not use it, it only means that from our opinion you should use the new data fetching methods.
html. Nextjs grabs your React app and calls getInitialProps. Data is fetched and the props will get passed to your component. React renders the fetched content for Next.
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) => { // ... }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With