- Published on
Automatically type NextJS static component props
- Authors
- Name
- Luke Wood
Automatically type NextJS static component props
Typing static props in NextJS apps is a bit annoying. This is because NextJS made the questionable decision to use modules as the unit of route bundling. There's an implicit relationship between:
- a components default export
- the return of
getStaticProps()
- a ton of other random NextJS methods
This is very hard for TypeScript to properly check, because from the perspective of Typescript a NextJS route is just a module. If you take this view, there is nothing wrong with returning a value from a function named getStaticProps()
that doesn't match the type of the input parameter of the default export which happens to be a function.
As a consequence, there's really not very good type inference for NextJS routes - but I've managed to write a few utility types to help.
NextJS is a great tool - but I am pretty annoyed that they made their abstraction for routes javascript files. If the abstraction they picked was a dataclass, i.e.
const route = {
getStaticProps, render: MyComponent
}
it would be trivial to type check the validity of our components. Still have a lot of respect for what the NextJS developers have built - you can't win them all :).
Here's the type I put on props to make sure that my types aren't wrong:
export async function getStaticProps() {
const about = await getMarkdownById('about.md');
return {
props: {
about: about.content
},
};
}
export default function Home(props: (Awaited<ReturnType<typeof getStaticProps>>)['props']) {
...
}
The type Awaited<ReturnType<typeof getStaticProps>>)['props']
gets you the output type of getStaticProps()
's props
return value. You can use this to establish a relationship between this and your rendering method.
If needed you can also merge it with getProps() via an &
invocation. Hopefully this saves someone time in the future.
Happy typing!