Property id does not exist on type {}

8k Views Asked by At
  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.

2

There are 2 best solutions below

0
Richard Gieg On BEST ANSWER

It seems like the TypeScript compiler is not aware of the correct type for history.location.state. You could try installing types for React:

npm install --save-dev @types/react @types/react-dom @types/react-router-dom

Alternatively, to just get around the error you could force state to type any:

const state = history.location.state;
const id = (state as any)?.id;
0
Mats On

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.