这是一些您可以使用的特定于 Next.js 的类型(types)。
对于 getStaticProps、getStaticPaths 和 getServerSideProps,你可以分别使用 GetStaticProps、GetStaticPaths 和 GetServerSideProps 类型(types):
import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next' export const getStaticProps: GetStaticProps = async context => { // ... } export const getStaticPaths: GetStaticPaths = async () => { // ... } export const getServerSideProps: GetServerSideProps = async context => { // ... }
以下是如何对 API 路由 使用内置类型(types)的示例:
import { NextApiRequest, NextApiResponse } from 'next' export default (req: NextApiRequest, res: NextApiResponse) => { // ... }
App你可以将 pages/_app.js 转换为 pages/_app.tsx 并使用内置类型(type) AppProps,如下所示:
import { AppProps } from 'next/app' function App({ Component, pageProps }: AppProps) { return <Component {...pageProps} /> } export default App
要将我们在基础课程中创建的博客应用程序转换为 TypeScript 编码,请更新以下文件:
components/date.js: 使用 此代码 更新为 date.tsx 文件components/layout.js: 使用 此代码 更新为 layout.tsx 文件lib/posts.js: 使用 此代码 更新为 posts.ts 文件pages/posts/[id].js: 使用 此代码 更新为 [id].tsx 文件pages/index.js: 使用 此代码 更新为 index.tsx 文件pages/_app.js:使用 此代码 更新为 _app.tsx 文件pages/api/hello.js: 使用 此代码 更新为 hello.ts 文件仅此而已!你的应用程序现在使用 TypeScript 编码了。
要了解有关使用 TypeScript 进行 Next.js 开发的更多信息,请查看 我们的 TypeScript 文档。