How do you specify the type of location.state in typescript? Trying to access location.state.x gives an error in typescript because location.state is of type {}.
Thanks
Not sure if this is the correct way but this is how I do it.
import {RouteComponentProps} from '@reach/router';
interface Props extends RouteComponentProps<{ location: { state: { myState: 'value' } } }> {
}
// and then your flavor of React
function MyComponent(props: Props) {
//...
}
const MyComponent: React.FC<Props> = (props) => {
//...
}
class MyComponent extends React.Component<Props> {
//...
}
Hope that helps.
You still get the problem once you are using the location from useLocation:
const location = useLocation();
location.state.x
Oh, didn't know that you were using useLocation.
From the solution above, you can use props.location.state which should give you what you want but if you insist on using useLocation it looks like the type definition for useLocation is using the WindowLocation type which is using an empty object as the default type. The useLocation isn't passing any generics to it so Typescript doesn't see that.
// in @types/reach__router
export type WindowLocation<S = LocationState> = Window['location'] & HLocation<S>;
export function useLocation(): WindowLocation;
The types package needs to be updated so you can do useLocation like you wanted.
// in @types/reach__router
export function useLocation<T = {}>(): WindowLocation<T>;
// in your own component
function MyComponent(props) {
const location = useLocation<{ myState: 'value' }>();
location.state.myState // should make typescript not complain anymore
}
any fix for this one?
@putrasurya Yes. Issue solved by @billy-le
I've got same issue and now fixed using that solution
you can map in state object by using Object.entries():
const {state} = useLocation();
Object.entries(state).map(([key, value]) => {
if (key == x)
console.log(value);
})
Most helpful comment
Not sure if this is the correct way but this is how I do it.
Hope that helps.