vercel / next.js

The React Framework
https://nextjs.org
MIT License
127.11k stars 27.01k forks source link

Correct type inference when using `fallback: true` #18705

Open tomdohnal opened 4 years ago

tomdohnal commented 4 years ago

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
}
dsbrianwebster commented 3 years ago

Adding on to this bug as I think the following is similar-enough to tackle in the same issue....

InferGetStaticPropsType will also fail when consider conditional returns from getStaticProps, like a notFound response.

props is never with a notFound condition is present

Screen Shot 2021-03-29 at 8 25 40 AM

works as expected with out a notFound condition

Screen Shot 2021-03-29 at 8 25 50 AM
flybayer commented 2 years ago

Looks like this will hopefully be solved with Typescript 4.9!

https://twitter.com/leeerob/status/1563540593003106306

image