TypeScript error after upgrading version 4 useParams () from react-router-dom Property 'sumParams' does not exist on type '{}'

JavascriptReactjsTypescriptReact Router-DomReact Dom

Javascript Problem Overview


I get a typeScript error after upgrading to version 4 Used in useParams () from react-router-dom

"typescript": "^4.0.2"

import { useParams } from 'react-router-dom';

const { sumParams } = useParams();

Property 'sumParams' does not exist on type '{}'. 

The project worked great and only after the upgrade does it throw an error

Javascript Solutions


Solution 1 - Javascript

useParams is generic. You need to tell typescript which params you are using by specifying the value of the generic

There are several ways to solve this

This is my favorite way

const { sumParams } = useParams<{ sumParams: string }>();

But there are a few more ways (:

OR

interface ParamTypes {
  sumParams: string;
}

Then in your Component

const { sumParams } = useParams<ParamTypes>();

OR

add any type without interface

const { sumParams } : any = useParams();

Note: that this way you will not be able to set it as a string

OR

More option for keemor:

const { sumParams } = useParams() as { 
  sumParams: string;
}

Solution 2 - Javascript

Another option is:

const { sumParams } = useParams() as { 
  sumParams: string;
}

Solution 3 - Javascript

To make it function as before, just add ":any"

const { sumParams } : any = useParams();

Solution 4 - Javascript

type ParamTypes {
  sumParams: string;
}

const { sumParams } = useParams<ParamTypes>()

this would be clean approach to take

Solution 5 - Javascript

For newer versions of the router, generic is changed from object to union of strings.

const { param1, param2 } = useParams<'param1' | 'param2'>();

Current useParams type in the react-router types looks like this:

export declare function useParams<Key extends string = string>(): Readonly<Params<Key>>;

Solution 6 - Javascript

You can also access the params from useRouteMatch if you already have it imported in your file

const curRoute = useRouteMatch();
// @ts-ignore
let sumParams  = curRoute.params.sumParams

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYoelView Question on Stackoverflow
Solution 1 - JavascriptYoelView Answer on Stackoverflow
Solution 2 - JavascriptkeemorView Answer on Stackoverflow
Solution 3 - JavascriptosoblancoView Answer on Stackoverflow
Solution 4 - JavascriptShailesh ParmarView Answer on Stackoverflow
Solution 5 - JavascriptMario PetrovicView Answer on Stackoverflow
Solution 6 - JavascriptCaleb C. AdainooView Answer on Stackoverflow