网站搜索

typescript - 在 Next.js 中使用 InferGetStaticPropsType 时如何修复 getStaticProps 类型?


我不知道为什么帖子属性会出现错误。错误描述是 属性 'body' 在类型 'never' 上不存在。

InferGetStaticPropsType<typeof getStaticPaths> 即使我用类型指定,也会出错吗?

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'
}

答案#1

看起来,在使用带参数的 getStaticProps 时,你必须使用 GetStaticProps 对函数进行类型标注,这样 InferGetStaticPropsType 才能获取正确的 props 类型。

import type { GetStaticProps, InferGetStaticPropsType } from 'next';

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 (
        <></>
    );
};