Property ‘xxx’ does not exist on type ‘object’ when object is of unknown type

Tags: , , ,



I am using Typescript in a react project which includes React Router (v6).

React Router returns a location object from the useLocation() hook

const location = useLocation()

which has a property called “state”. State is an object which can be passed to any url and can have any properties you want. It simply has a type of “Object” because the user can set any number of properties on the state.

The trouble comes when I come to access a property which may or not be part of the state. My JS (non-typescript) code had this…

if(location.state && location.state.modals === true){...do something}

But the second part of the expression gives me an error… Property ‘modals’ does not exist on type ‘object’

Now, I know that a generic object (which is the type of the state, set by the library author, not me) doesn’t have a property called .modals but I can’t do a lot about that, it could have literally any propery depending on what page of the app we’re currently in and what’s contained in the state at that moment.

I’m at a bit of a loss about how to fix it.

Answer

One way to get around this problem is to use type assertion via the “as” keyword to tell the compiler to consider the state object as any type e.g.

if(location.state && (location.state as any).modals){...do something}

This would allow state to have any value but we both know that it would be better to deal with a more rigidly defined type!



Source: stackoverflow