在带有 TypeScript 的 Next.js 中使用 getInitialProps [英] Using getInitialProps in Next.js with TypeScript

查看:19
本文介绍了在带有 TypeScript 的 Next.js 中使用 getInitialProps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从文档、Next.js 5.0 公告和互联网上的各种文章来看,Next.js 似乎很好地支持 TypeScript,并且很多人都在使用它.

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.

但这些线程表明,对于 Next.js 应用程序至关重要的 getInitialProps 不起作用:

But these threads suggest that getInitialProps, which is vital to Next.js apps, doesn't work:

我该如何解决?在类和功能组件中,当我执行 ComponentName.getInitialProps = async function() {...} 时,我收到以下错误:

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

推荐答案

Edit 2021/04/23: 我下面的回答也过时了

请参阅 Next.js 文档 对于当前使用新类型和命名导出来键入数据获取方法的建议.

Edit 2021/04/23: My answer below is also out of date

Please see the Next.js docs for the current recommendation for typing data fetching methods using new types and named exports.

tl;博士:

import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'

export const getStaticProps: GetStaticProps = async (context) => {
  // ...
}

export const getStaticPaths: GetStaticPaths = async () => {
  // ...
}

export const getServerSideProps: GetServerSideProps = async (context) => {
  // ...
}


过时(但功能正常)的答案:

上述答案已经过时,因为 Next.js 现在正式支持 TypeScript(公告 这里)

此版本的一部分是更好的 TypeScript 类型,Next.js 的大部分内容都是用 TypeScript 本身编写的.这意味着 @types/next 包将被弃用,取而代之的是官方的 Next.js 类型.

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.

相反,您应该导入 NextPage type 并将其分配给您的组件.您还可以使用 NextPageContext 类型键入 getInitialProps.

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
}

这篇关于在带有 TypeScript 的 Next.js 中使用 getInitialProps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆