Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type error when using function with the return type NextPage

So the following code works:

const HomePage: NextPage = () => (
  <div>
    <div>HomePage</div>
  </div>
);

However I would like to comply with the Airbnb's style guide, which in this case requires you to use a named function, arriving at this code:

function HomePage(): NextPage {
  return (
    <div>
      <div>HomePage</div>
    </div>
  )
}

However the compiler gives the following error to the code above:

Type 'Element' is not assignable to type 'NextPage<{}, {}>'.
  Type 'ReactElement<any, any>' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext): {} | Promise<{}>; }'.
    Type 'ReactElement<any, any>' is not assignable to type 'FunctionComponent<{}>'.
      Type 'ReactElement<any, any>' provides no match for the signature '(props: { children?: ReactNode; }, context?: any): ReactElement<any, any> | null'.ts(2322)

I can bypass the error by either not specifying the type, or by casting the return to as unknown as NextPage, both of which look like workarounds rather than a correct solution.

What is the correct way of using named functions in this case?

like image 572
keke Avatar asked Oct 26 '25 21:10

keke


1 Answers

Those two code blocks are not exactly the same.

In the first one, you're correctly using NextPage to type the variable HomePage which is a function.

In the second one, you're incorrectly using NextPage to type HomePage's return value (which is not the same as the function itself).

You can type HomePage's return value in several ways, using JSX.Element, React.ReactElement or React.ReactNode.

function HomePage(): JSX.Element {
  return (
    <div>
      <div>HomePage</div>
    </div>
  )
}

Note that there's nothing wrong in typing the function as you are in the first code block, and is actually the recommended way in Next.js. It provides typings for both the component's props and return value.

like image 126
juliomalves Avatar answered Oct 28 '25 10:10

juliomalves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!