Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 410
Yoel Avatar asked Aug 30 '20 18:08

Yoel


4 Answers

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;
}
like image 133
Yoel Avatar answered Oct 05 '22 09:10

Yoel


Another option is:

const { sumParams } = useParams() as { 
  sumParams: string;
}
like image 31
keemor Avatar answered Oct 05 '22 09:10

keemor


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

const { sumParams } : any = useParams();
like image 23
osoblanco Avatar answered Oct 05 '22 09:10

osoblanco


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>>;
like image 38
Mario Petrovic Avatar answered Oct 05 '22 07:10

Mario Petrovic