Reputation: 15366
next.js advices the following pattern to access to the route params:
const Page = withRouter((props) => (
<p>{props.router.query.title}</p>
))
Now the problem is that in TypeScript the code above would show an error because router
and query
could be undefined. It has to be rewritten either as
props.router!.query!.title
or as
props.router && props.router.query && props.router.query.title
both ways are bad in my opinion. In the first one we just forcing compiler to ignore the error and in other bloat the code with unnecessary noise.
Is there a better way to access the route params?
Upvotes: 9
Views: 4802
Reputation: 549
There's an operator called optional chaining ?.
that let's you read the value from a object chain without having to validate that each reference is valid. Instead of causing an error it will return undefined.
So you can do:
const Page = withRouter((props) => (
<p>{props.router?.query?.title}</p>
))
Upvotes: 2
Reputation: 15006
There is a proposal for optional chaining in JavaScript, but seems like it'll take a while before it's finalized.
You're correct on avoiding props.router!.query!.title
to ignore the typecheck errors. You would have to conditionally check for the existing properties as you suggested: props.router && props.router.query && props.router.query.title
I usually create a helper function to accept an object and fetch a nested property from it. Or better you can use an existing library such as lodash get:
import get from 'lodash/get'
...
const title = get(props, ['router', 'query', 'title'])
...
Upvotes: 2