I’m writing code for server error handling using typescript in react(version 6).
But i got the error from useLocation and state.
useLocation got error which message is "Expected 0 type arguments, but got 1.ts(2558)" So if i erase then the error disappeared but still state have errors like "Object is of type ‘unknown’.ts(2571) "
import { Button, Container, Divider, Paper, Typography } from "@mui/material";
import { useHistory, useLocation } from "react-router";
export default function ServerError() {
const history = useHistory();
const { state } = useLocation<any>();
return (
<Container component={Paper}>
{state?.error ? (
<>
<Typography variant='h3' color='error' gutterBottom>{state.error.title}</Typography>
<Divider />
<Typography>{state.error.detail || 'Internal server error'}</Typography>
</>
) : (
<Typography variant='h5' gutterBottom>Server Error</Typography>
)}
<Button onClick={() => history.push('/catalog')}>Go back to the store</Button>
</Container>
)
}
>Solution :
It looks like the type of state is unknown in the useLocation type definition: https://reactrouter.com/docs/en/v6/hooks/use-location
Thus, you can use a cast to cast the state type as any to avoid those errors:
const location = useLocation();
const state = location.state as any;
Or, if you know the type of location.state, you can cast it to a custom object type:
const location = useLocation();
const state = location.state as { error?: { title: string; detail?: string } }
