`Is there a way to resolve the getStaticProps type issue in Next.js while utilizing InferGetStaticPropsType?`

I'm puzzled by an error that occurred with post props. The error message reads as follows:

Property 'body' does not exist on type 'never'
.

https://i.stack.imgur.com/zYlxc.png

Even when I specify the type, can there still be an error with 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;

When I inspect console.log(post), its structure looks like this:

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

Answer №1

When utilizing the getStaticProps function with parameters, it is essential to ensure that the function is defined with the GetStaticProps type in order for the InferGetStaticPropsType to correctly infer the props type.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating the parent scope in Angular using TypeScript

Is there a way to access the parent Controller's scope from within the TypeScript class? Here is the code snippet: export class EntityOverviewCtrl extends AbstractCtrl { public static $inject = ["$state", "$http", "CurrentSession"]; publi ...

When trying to style a Material UI component in Mui v5, no matches for overloads were found

In my attempt to enhance the style of a Material UI Component (TextField) shown in the image, I encountered an error that seems to persist no matter what troubleshooting steps I take. Interestingly enough, I never faced such issues when working with styled ...

Guidance on incorporating a function as a prop in React using TypeScript

I'm currently learning TypeScript with React and ran into an issue. I attempted to pass a function as a property from my App component to a child component named DataForm. However, I encountered the following error: Type '(f: any) => any&ap ...

Having difficulty forming queries correctly using TypeScript, React, and GraphQL

Apologies for the potentially naive question, but I am new to working with GraphQL and React. I am attempting to create a component that contains a GraphQL query and incoming props. The props consist of a query that should be passed into the GraphQL query. ...

Does adding .catch resolve a promise?

Being new to typescript / javascript, I have limited knowledge about promises. My current scenario involves creating three distinct promises within a cloud-function and subsequently returning them using Promise.all([promise1, promise2, promise3]). Each of ...

typescript encounters issues with union type while trying to access object properties

I'm puzzled by the errors I'm encountering in my IDE with the following code: I defined some interfaces/types interfaces/types: interface GradientColor { type: string; value: { angle: string | number; colours: string[]; }; } inte ...

Issue: React-Firebase-Hooks failing to retrieve dataHaving trouble with React-F

I've been utilizing the React-Firebase-Hooks package in my project, but I'm encountering some difficulties with its usage. In the code snippet below, the user.data().username is displayed correctly. However, when I try to use it within useState, ...

I am feeling lost when it comes to managing state/props and making changes to the user interface in

My React app uses componentDidMount to fetch data from an external API and updates every second. I want the UI to display the current track name when it changes. While my code works fine with console logging, the UI fails to update. I am under the impress ...

Executing a function when a user chooses to exit a webpage using the @HostListener('window:beforeunload') method

Utilizing @HostListener('window:beforeunload') allows me to detect when a user navigates away from the page, prompting a dialog window to open. I wish for an event to be triggered or a method to be executed if the user chooses to leave the page. ...

Using lambda expressions to sort through an array of objects in React

My goal is to create a delete button that removes items from a list and updates the state variable accordingly. public OnDeleteClick = (): void => { const selectionCount = this._selection.getSelectedCount(); let newArray = this.state.items; for ...

Ways to elegantly replace an object with thorough validation of its embedded properties

Consider the following code snippet: interface Human{ name:string age:number dimensions : { height:number width:number } } const base : Human ={ name:"Base", age:12, dimensions : { height:190, width:99 } }; const child ...

Troubleshooting an issue with asynchronous reactive form validators in Angular

I encountered an issue where I need to access a service that sends an http request to an API to verify the existence of a given username. Snippet from Auth component: usernameCheck(username: string){ return this.http.get(this.baseUrl + "usernamecheck?u ...

Can we determine the data type of an object based on a property within an interface?

Here is my current interface: MyInterface { prop1?: string, prop2?: string, } Now, I am looking to introduce an alternative property that mirrors the content of the existing properties but also infers if any properties are defined. For instance: ...

Simulating chained responses in Express using JEST

I am relatively new to using jest and typescript, currently working on creating a unit test for a controller function in jest import { Request, Response } from 'express'; const healthCheck = (_req: Request, _res: Response) => { const value ...

Can TestCafe be used to simulate pressing the key combination (Ctrl + +)?

I've been having a tough time trying to use the key combination specified in the title (Ctrl + +). So far, this is what I've attempted: 'ctrl+\+' 'ctrl+\\+' Does TestCafe even support this key combination? T ...

A guide on utilizing the TypeScript compilerOptions --outDir feature

Recently, I encountered an error message from the compiler stating: Cannot write file 'path/file.json' because it would overwrite input file. After some investigation, most of the solutions suggested using outDir to resolve this issue. Although t ...

Utilizing Nodemailer and ReadableStreams to send email attachments stored in S3

My current challenge involves sending emails with Nodemailer that include attachments hosted in S3, utilizing JS AWS SDK v3. The example provided in the Nodemailer documentation demonstrates how to send an attachment using a read stream created from a file ...

Retrieving the value of a <select> element using React.useState in a Nextjs environment

Encountering an issue in Nextjs involving the useState function from React. There is a select element with multiple options. Upon selection, the useState should store the value of the selected option. const [value, setValue] = useState('') ... ...

Can you explain the true meaning behind this specific type definition?

Since starting to dive into TypeScript recently, I came across an express server written in TS while browsing the Internet. However, I am struggling to comprehend the type definition of the 'middlewares' argument. Despite attempting to research i ...

Typescript React Union type

I have developed a Card component with two different variants: Wrapper and Dashboard. Each variant comes with its own set of props. export type DashboardProps = { variant: CardVariant.Dashboard, primaryText: string, secondaryText: string, icon: Ove ...