I have a location that returns a Location that has an undefined state (unknown). I can't figure out how I can extend the Location interface type so that I don't get an error that form doesn't exist.
TS2571: Object is of type 'unknown'.
const location: Location = useLocation();
const fromPage: string = location.state?.form || ENDPOINTS.GET_LIST_REPORTS;
CodePudding user response:
You can use the generic type of useLocation()
.
interface LocationState {
from: {
pathname: string;
};
}
const location = useLocation<LocationState>();
const { from } = location.state || { from: { pathname: "/" } };
Code from answer in this post. https://stackoverflow.com/a/61669105/4490246
CodePudding user response:
You can extend your Location
with type
type ExtendedLocation = Location & { state?: { form: string } }
const location: ExtendedLocation = useLocation();
const fromPage: string = location.state?.form || ENDPOINTS.GET_LIST_REPORTS;
Or with an extended interface
interface ExtendedLocation extends Location {
state?: { form: string }
}
const location: ExtendedLocation = useLocation();
const fromPage: string = location.state?.form || ENDPOINTS.GET_LIST_REPORTS;