如何使 Next.js getStaticProps 与打字稿一起使用 [英] How to make Next.js getStaticProps work with typescript

查看:22
本文介绍了如何使 Next.js getStaticProps 与打字稿一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用启用了 typescript 功能的 Next.js

尝试使用此处描述的 getStaticProps

输入 '() =>{ 道具:{ 主机:字符串;};}' 不可分配给类型 'GetStaticProps<{ [key: string]: any;}, ParsedUrlQuery>'.输入'{道具:{主机:字符串;};}' 缺少类型 'Promise<GetStaticPropsResult<{ [key: string]: any; 中的以下属性}>>':然后,catch,[Symbol.toStringTag],finallyts(2322)

我是 typescript 的新手,所以我很难弄清楚它想要什么,

如果有任何帮助,我将不胜感激,在此先感谢

这是整个页面的代码

从'next/head'导入Head从 '../styles/Home.module.css' 导入样式从反应"导入反应从下一个"导入 { GetStaticProps, GetStaticPropsContext }接口道具 {主机:字符串}const 主页:React.FC<Props>=(道具)=>{返回 (<div 类名={styles.container}><头><title>创建下一个应用程序</title><link rel="图标";href="/favicon.ico";/></头><主类名={styles.main}>aa:{props.host}<h1 className={styles.title}>欢迎来到 <a href="https://nextjs.org">Next.js!</a></h1><p className={styles.description}>开始编辑 <code className={styles.code}>pages/index.js</code></p><div 类名={styles.grid}><a href="https://nextjs.org/docs"className={styles.card}><h3>文档 &rarr;</h3><p>查找有关 Next.js 功能和 API 的深入信息.</p></a><a href="https://nextjs.org/learn"className={styles.card}><h3>学习&rarr;</h3><p>在带有测验的互动课程中了解 Next.js!</p></a>

解决方案

您好,但上面的答案都没有帮助我.

我快速阅读了文档:https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation

并发现您的 getStaticProps 的正确类型应该是:

import { GetStaticProps } from 'next'export const getStaticProps: GetStaticProps = async (context) =>{//...}

然后在你的组件中:

import { InferGetStaticPropsType } from 'next'输入帖子 = {作者:字符串内容:字符串}导出 const getStaticProps = async () =>{const res = await fetch('https://.../posts')常量帖子: Post[] = await res.json()返回 {道具: {帖子,},}}功能博客({帖子}:InferGetStaticPropsType<getStaticProps类型>){//将帖子解析为 Post[] 类型}导出默认博客

这会从 GetStaticProps 自动生成一个类型到你的组件,它对我有用 100%

I am using Next.js with typescript feature enabled

Trying to use getStaticProps as described here https://nextjs.org/docs/basic-features/typescript

With GetStaticProps type

export const getStaticProps: GetStaticProps = () => {
    return {
        props: {
            host: process.env.DB_HOST.toString(),
        },
    }
}

I am getting error like this

Type '() => { props: { host: string; }; }' is not assignable to type 'GetStaticProps<{ [key: string]: any; }, ParsedUrlQuery>'.
  Type '{ props: { host: string; }; }' is missing the following properties from type 'Promise<GetStaticPropsResult<{ [key: string]: any; }>>': then, catch, [Symbol.toStringTag], finallyts(2322)

I am new to typescript so it's hard for me to figure out what it wants,

I would appreciate any help, thanks in advance

Here is the entire page code

import Head from 'next/head'
import styles from '../styles/Home.module.css'
import React from 'react'
import { GetStaticProps, GetStaticPropsContext } from 'next'

interface Props {
    host: string
}

const Home: React.FC<Props> = (props) => {
    return (
        <div className={styles.container}>
            <Head>
                <title>Create Next App</title>
                <link rel="icon" href="/favicon.ico" />
            </Head>

            <main className={styles.main}>
                aa:{props.host}
                <h1 className={styles.title}>
                    Welcome to <a href="https://nextjs.org">Next.js!</a>
                </h1>
                <p className={styles.description}>
                    Get started by editing <code className={styles.code}>pages/index.js</code>
                </p>
                <div className={styles.grid}>
                    <a href="https://nextjs.org/docs" className={styles.card}>
                        <h3>Documentation &rarr;</h3>
                        <p>Find in-depth information about Next.js features and API.</p>
                    </a>

                    <a href="https://nextjs.org/learn" className={styles.card}>
                        <h3>Learn &rarr;</h3>
                        <p>Learn about Next.js in an interactive course with quizzes!</p>
                    </a>

                    <a
                        href="https://github.com/vercel/next.js/tree/master/examples"
                        className={styles.card}
                    >
                        <h3>Examples &rarr;</h3>
                        <p>Discover and deploy boilerplate example Next.js projects.</p>
                    </a>

                    <a
                        href="https://vercel.com/import?filter=next.js&utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
                        className={styles.card}
                    >
                        <h3>Deploy &rarr;</h3>
                        <p>Instantly deploy your Next.js site to a public URL with Vercel.</p>
                    </a>
                </div>
            </main>

            <footer className={styles.footer}>
                <a
                    href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
                    target="_blank"
                    rel="noopener noreferrer"
                >
                    Powered by <img src="/vercel.svg" alt="Vercel Logo" className={styles.logo} />
                </a>
            </footer>
        </div>
    )
}

export const getStaticProps: GetStaticProps = () => {
    return {
        props: {
            host: process.env.DB_HOST.toString(),
        },
    }
}

export default Home

解决方案

Hi Ran in to your issue but none of the answers above helped me.

I had a quick read in the documentation: https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation

and found out that you the correct type for your getStaticProps should be:

import { GetStaticProps } from 'next'

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

Then in your component:

import { InferGetStaticPropsType } from 'next'

type Post = {
  author: string
  content: string
}

export const getStaticProps = async () => {
  const res = await fetch('https://.../posts')
  const posts: Post[] = await res.json()

  return {
    props: {
      posts,
    },
  }
}

function Blog({ posts }: InferGetStaticPropsType<typeof getStaticProps>) {
  // will resolve posts to type Post[]
}

export default Blog

This will autogenerate a type from GetStaticProps to your component it worked for me 100%

这篇关于如何使 Next.js getStaticProps 与打字稿一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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