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.
Top comments (2)
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.
so what do you suggest should be done to solve this error?