使用返回类型为 NextPage 的函数时出现类型错误

kek*_*eke 4 typescript reactjs next.js

所以下面的代码有效:

const HomePage: NextPage = () => (
  <div>
    <div>HomePage</div>
  </div>
);
Run Code Online (Sandbox Code Playgroud)

不过,我想遵守 Airbnb 的风格指南,在本例中,它要求您使用命名函数,得出以下代码:

function HomePage(): NextPage {
  return (
    <div>
      <div>HomePage</div>
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

然而,编译器对上面的代码给出了以下错误:

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)
Run Code Online (Sandbox Code Playgroud)

我可以通过不指定类型或将 return 强制转换为 来绕过错误as unknown as NextPage,这两种方法看起来都像是解决方法,而不是正确的解决方案。

在这种情况下使用命名函数的正确方法是什么?

jul*_*ves 7

这两个代码块并不完全相同。

在第一个中,您正确地使用了函数变量的NextPage类型HomePage

在第二个中,您错误地使用了NextPageto typeHomePage返回值(与函数本身不同)。

您可以使用、或 等HomePage多种方式键入 的返回值。JSX.ElementReact.ReactElementReact.ReactNode

function HomePage(): JSX.Element {
  return (
    <div>
      <div>HomePage</div>
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

请注意,在第一个代码块中键入函数没有任何问题,这实际上是 Next.js 中推荐的方式。它提供组件的 props 和返回值的类型。