Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property id does not exist on type {}

  const state = history.location.state;
  const id = state?.id;

Following is the typescript error:

Property 'id' does not exist on type '{}'.  TS2339

I am getting the id value from history.location.state i.e from react-router I am sending the id prop as state to history.push("pathname",{id:"some value"}.

So,for this code is working but it throws with a typescript error.

Please help me how to fix the above typescript error.

like image 320
Sai Avatar asked Dec 18 '25 21:12

Sai


1 Answers

Inspect the types, and try to decrypt them. 🤪

TL;DR

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

This is what the function definition looks like this:

export function useParams<Params extends { [K in keyof Params]?: string } = {}>(): Params;

If you want an id you add an id, and so on for any other Params you want. K is a key in the list of parameters and the type is always a string.

like image 162
Mats Avatar answered Dec 24 '25 03:12

Mats



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!