使用TypeScript在Next.js中使用getInitialProps [英] Using getInitialProps in Next.js with TypeScript
问题描述
从文档,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:
- https://github.com/zeit/next.js/issues/3396
- https://github.com/zeit/next.js/issues/1651
- https://github.com/DefinitelyTyped/DefinitelyTyped/issues/23356
- https://github.com/zeit/next.js/issues/3396
- https://github.com/zeit/next.js/issues/1651
- https://github.com/DefinitelyTyped/DefinitelyTyped/issues/23356
我该如何解决?在类和功能组件中,当我执行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'.
推荐答案
上述答案已过时,因为Next.js现在正式支持TypeScript(公告
The above answers are out of date since Next.js now officially supports TypeScript (announcement here)
此发行版的一部分是更好的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.
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屋!