41

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

Yoel
  • 3,793
  • 3
  • 15
  • 39

3 Answers3

98

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;
}
Yoel
  • 3,793
  • 3
  • 15
  • 39
  • 2
    do you know what changed between TS versions to cause this to become an error? I couldn't find anything in the change log that suggested this would change. – mtoor Sep 26 '20 at 00:30
  • 2
    Update: I did a binary search through typescript versions on npm, and this started becoming an issue between version 4.0.0-dev.20200624 and 4.0.0-dev.20200625. You can check out the differences between those versions here: https://diff.intrinsic.com/typescript/4.0.0-dev.20200624/4.0.0-dev.20200625 – mtoor Sep 26 '20 at 01:36
7

Another option is:

const { sumParams } = useParams() as { 
  sumParams: string;
}
keemor
  • 736
  • 11
  • 12
4

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

const { sumParams } : any = useParams();
Yoel
  • 3,793
  • 3
  • 15
  • 39
osoblanco
  • 420
  • 2
  • 9