Skip to content

getStaticProps not working well with TypeScript #16522

Answered by janluke
deadcoder0904 asked this question in Help
Discussion options

You must be logged in to vote

I'm new to next.js and TypeScript (in fact, I ended up here after following the tutorial) but I did as following:

import { ParsedUrlQuery } from 'querystring';

type Props = {
   post: PostData
}

interface Params extends ParsedUrlQuery {
   id: string,
}

export const getStaticProps: GetStaticProps<Props, Params> = async (context) => {
   const params = context.params!       // ! is a non-null assertion 
   const post = await getPost(params.id)
   return {
      props: { post }
   }
}

Each field of context is declared as optional, so you need to check for null or use a type assertion like I did for params.

EDIT:

  • added import of ParsedUrlQuery
  • changed 1st line of getStaticProps: use the …

Replies: 18 comments 38 replies

Comment options

You must be logged in to vote
1 reply
@janluke
Comment options

Comment options

You must be logged in to vote
1 reply
@poncianodiego
Comment options

Comment options

You must be logged in to vote
11 replies
@Kobold
Comment options

@ghost
Comment options

@Lastor-Chen
Comment options

@RobertaMelo
Comment options

@yourcodesnotworking
Comment options

Answer selected by steven-tey
Comment options

You must be logged in to vote
6 replies
@Pravasith
Comment options

@GorvGoyl
Comment options

@janluke
Comment options

@janluke
Comment options

@RobertaMelo
Comment options

Comment options

You must be logged in to vote
2 replies
@valdeniomarinho
Comment options

@philsmithies
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@rokinsky
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
7 replies
@lawrence-witt
Comment options

@janluke
Comment options

@lawrence-witt
Comment options

@lawrence-witt
Comment options

Comment options

You must be logged in to vote
5 replies
@janluke
Comment options

@lawrence-witt
Comment options

@janluke
Comment options

@lawrence-witt
Comment options

@janluke
Comment options

Comment options

You must be logged in to vote
2 replies
@lucaoskaique
Comment options

@cevaris
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@Toinouze
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@badalsaibo
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet