Skip to content

Correct type inference when using fallback: true #18705

Open
@tomdohnal

Description

@tomdohnal

Feature request

Is your feature request related to a problem? Please describe.

When I'm using fallback: true in getStaticPaths and using InferGetStaticPropsType to infer the props, it doesn't take the fact that the fallback page might load into account. It assumes that the props will always get passed to the page.

import { InferGetStaticPropsType } from 'next'

type Post = {
  author: string
  content: string
}

export const getStaticPaths = async ({params}) => {
  const res = await fetch(`https://.../posts/${params.id}`)
  const posts: Post[] = await res.json()

  return {
    paths: [{ params: { id: '1' }],
    fallback: true
  }
}

export const getStaticProps = async ({params}) => {
  const res = await fetch(`https://.../posts/${params.id}`)
  const posts: Post[] = await res.json()

  return {
    props: {
      posts,
    },
  }
}

function Blog({ posts }: InferGetStaticPropsType<typeof getStaticProps>) {
  // will resolve posts to type Post[] although it will be undefined if router.isFallback is true
}

export default Blog

Describe the solution you'd like

I'd like to have the possibility to pass the getStaticPaths as a second argument to the InferGetStaticPropsType type like this:

InferGetStaticPropsType<typeof getStaticProps, typeof getStaticPaths>

The InferGetStaticPropsType type would infer if the props can be an empty object based upon the value of fallback returned from getStaticPaths.

Describe alternatives you've considered

An alternative is to type the props manually if using fallback: true like this:

function Blog({ posts }: InferGetStaticPropsType<typeof getStaticProps> | {}) {
  // will resolve posts to type Post[] although it will be undefined if router.isFallback is true
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    TypeScriptRelated to types with Next.js.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions