Error: useParams Not Destructuring In Typescript
Victor Olaoye
Posted on September 3, 2022
I've seen this error in the code block below cause issues for developers who are just starting out with TypeScript. I'm going to show you how to solve this error.
const { token } = useParams();
First, you need to be aware that typescript can't destructure generic plain objects like {}
which means useParams() is a generic. Peradventure, you might have also tried using this code block below:
const { token } = useParams() as any
The code block above is very wrong because any
can't just be thrown around in this case. The keyword any
should only be used when the object can be of any type, in our case here we know the properties and the type of our object, therefore, any
shouldn't be used in this scenario.
Side Note: If you know anything about the property of your object or what it will hold, then the keyword any
shouldn't be used. It defeats the entire purpose of using typescript in this context.
Now, you might be wondering; what is the best possible solution. You need to tell TypeScript the value of the generic. Say, the value of our generic is a string. Then we write it like this:
const { token } = useParams<{token?: string}>()
From the above code, we're simply telling TypeScript that the value of our token is either a string or undefined. The ?
in our code is an optional operating chaining operator in TypeScript. By now, your error should have been solved and doubts cleared.
Posted on September 3, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.