How to make Next.js getStaticProps work with typescript

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%

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)