【问题标题】:Nextjs - Error building Type error: Object is of type 'unknown'Nextjs - 错误构建类型错误:对象的类型为“未知”
【发布时间】:2022-01-12 05:53:25
【问题描述】:

我正在使用 prismic 制作应用程序,生成帖子,但在 GetServerSideProps 中,我遇到类型错误:对象类型为“未知”错误。我已经尝试过打字,但它不起作用或者我做得不对,有人可以帮我解决这个问题吗a

import { GetServerSideProps } from "next";
import Head from "next/head";
import { RichText } from "prismic-dom";
import { getPrismicClient } from "../../services/prismic";
import styles from "./post.module.scss";
import { ParsedUrlQuery } from "querystring";

interface IParams extends ParsedUrlQuery {
  slug: string;
}
interface PostProps {
  post: {
    slug: String;
    title: String;
    content: string;
    updatedAt: String;
  };
}

export default function Post({ post }: PostProps) {
  return (
    <>
      <Head>
        <title>{post.title} | Ignews</title>
      </Head>
      <main className={styles.container}>
        <article className={styles.post}>
          <h1>{post.title}</h1>
          <time>{post.updatedAt}</time>
          <div
            className={styles.postContent}
            dangerouslySetInnerHTML={{ __html: post.content }}
          />
        </article>
      </main>
    </>
  );
}

export const getServerSideProps: GetServerSideProps<PostProps> = async (
  context
) => {
  const { slug } = context.params as IParams;
  const prismic = getPrismicClient();

  const response = await prismic.getByUID("publications", String(slug), {});
  const post = {
    slug,
    title: RichText.asText(response.data.title), //Type error: Object is of type 'unknown'.
    content: RichText.asHtml(response.data.content), //Type error: Object is of type 'unknown'.
    updatedAt: new Date(response.last_publication_date).toLocaleDateString(
      "pt-BR",
      {
        day: "2-digit",
        month: "long",
        year: "numeric",
      }
    ), //Type error: Object is of type 'unknown'.
  };
  return {
    props: {
      post,
    },
  };
};

【问题讨论】:

  • 您能告诉我们您是如何尝试输入的吗?可以分享一下getPrismicClient函数的代码吗?

标签: typescript next.js


【解决方案1】:

很可能是这样的:

  const response = await prismic.getByUID("publications", String(slug), {});

返回错误。在try/catch执行它

  try{
     const response = await prismic.getByUID("publications", String(slug), {});
}
   catch(e){
     console.log("error in fetching", e.message)
}

更好的方法是

updatedAt: new Date(response?.last_publication_date).toLocaleDateString

【讨论】:

  • 我试过了,但是错误依然存在,如果我在getServerSideProps里面使用try里面的错误,我试着把response?。但即便如此,它也会给构建带来错误,在开发中它可以正常工作,但在生产中它会给出这个错误,类型错误:对象是“未知”类型。
  • 你得到回应了吗?安慰。记录它
  • 是的,在开发中一切正常,即使我进入 nextjs 设置并将其忽略构建中的 ts,它也可以正常工作,问题是没有它它会一直给出这个好像没有输入一样的错误
猜你喜欢
  • 2021-11-16
  • 2022-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多