'Nextjs how to type Error page with typescript

How can type an nextjs Error page with Typescript

I've tried with:

interface ErrorProps {
  statusCode: number;
}
function Error({ statusCode }: ErrorProps) {
  return (
    <p>
      {statusCode
        ? `An error ${statusCode} occurred on server`
        : "An error occurred on client"}
    </p>
  );
}

interface InitialProps {
  res: NextApiResponse;
  err: NextApiResponse;
}
Error.getInitialProps = ({ res, err }: InitialProps) => {
  const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
  return { statusCode };
};

but not sure it's the right way



Solution 1:[1]

According to Next's own documentation ->

pages/_error.js is only used in production. In development you’ll get an error with the call stack to know where the error originated from.

Solution 2:[2]

I am working perfectly with the code below. Check this!

See more details on Next.js error page for typescript

import { NextPage, NextPageContext } from 'next';


interface Props {
    statusCode?: number
}

const Error: NextPage<Props> = ({ statusCode }) => {
    return (
        <p>
        {statusCode
            ? `An error ${statusCode} occurred on server`
            : "An error occurred on client"}
        </p>
    );
  }
  
  Error.getInitialProps = ({ res, err }: NextPageContext) => {
    const statusCode = res ? res.statusCode : err ? err.statusCode : 404
    return { statusCode }
  }
  
  export default Error

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Davi Lacerda
Solution 2 jianan1104