【问题标题】:How fix getStaticProps type (in Typescript)如何修复 getStaticProps 类型(在 Typescript 中)
【发布时间】:2022-08-16 07:37:57
【问题描述】:

不知道为什么post props有错误 错误描述为Property \'body\' does not exist on type \'never\'

InferGetStaticPropsType 即使我指定了类型也会有错误吗?

interface IParams {
  params: {
    slug: string;
  };
}

export const getStaticPaths = async () => {
  return {
    paths: allPosts.map((p) => ({ params: { slug: p._raw.flattenedPath } })),
    fallback: false,
  };
};

export async function getStaticProps({ params }: IParams) {
  const post: Post = allPosts.find(
    (post) => post._raw.flattenedPath === params.slug
  ) as Post;

  console.log(post);
  return {
    props: {
      post,
    },
  };
}

export default Detail;

当我检查console.log(post)时,它的结构如下。

{
  title: \'good ! \',
  date: \'2022-08-10T00:00:00.000Z\',
  description: \'this is description\',
  tags: \'Typescript\',
  body: {
    raw: \'## hello world\',
    code: \'\' },
  _id: \'second.mdx\',
  _raw: {
    sourceFilePath: \'second.mdx\',
    sourceFileName: \'second.mdx\',
    sourceFileDir: \'.\',
    contentType: \'mdx\',
    flattenedPath: \'second\'
  },
  type: \'Post\'
}
```
  • 不应该是const Detail = (post: InferGet..... 吗?
  • 好像类型坏了。你可能想搜索他们的 GitHub 问题,如果你没有找到任何东西,你可以打开你自己的。

标签: typescript next.js


【解决方案1】:

看起来当使用带有参数的getStaticProps 时,您必须使用GetStaticProps 类型键入函数,以便InferGetStaticPropsType 选择正确的道具类型。

type PropsType = { post: Post };
type ParamsType = ParsedUrlQuery & { params: { slug: string } };

export const getStaticProps: GetStaticProps<PropsType, ParamsType> = async ({ params }) => {
    const post: Post = allPosts.find(
        (post) => post._raw.flattenedPath === params.slug
    ) as Post;

    return {
        props: {
            post
        }
    };
}

const Detail = ({ post }: InferGetStaticPropsType<typeof getStaticProps>) => {
    //            ^ Should pick up `Post` type instead of `never`
    return (
        <></>
    );
};

【讨论】:

    猜你喜欢
    • 2020-02-19
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2020-02-24
    • 2019-08-25
    • 2017-10-12
    相关资源
    最近更新 更多