DEV Community

Victor Olaoye
Victor Olaoye

Posted on

Error: useParams Not Destructuring In Typescript

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();
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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}>()
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

Collapse
 
fjones profile image
FJones

So in order for tsc not to crap itself about the return value, you need to tell it - in the place you're calling useParams - what it's going to return.

Is anyone gonna come up with an idiomatic way of doing this, or is it just idiotic like that? I mean, this seems to very much defeat the purpose of TS, and makes you write the same potential error twice.

Collapse
 
olaoyevick profile image
Victor Olaoye

so what do you suggest should be done to solve this error?