React TypeScript: Correct type for useLocation() from react-router-dom React TypeScript: Correct type for useLocation() from react-router-dom reactjs reactjs

React TypeScript: Correct type for useLocation() from react-router-dom


You can create a particular type or interface to describe your location state and then use it when calling a useLocation hook:

import React from "react";import { useLocation } from "react-router-dom";interface LocationState {  from: {    pathname: string;  };}const AuthLayer: React.FC = (props) => {  const location = useLocation<LocationState>();  const { from } = location.state || { from: { pathname: "/" } };  return <p></p>;};export default AuthLayer;


You can use Location from 'history'.

import React from "react";import { Location } from "history";import { useLocation } from "react-router-dom";const AuthLayer: React.FC = (props) => {  const location = useLocation<Location>();  const { from } = location.state || { from: { pathname: "/" } };  return <p></p>;};export default AuthLayer;


Type Assertion would work here.

import React from "react";import { useLocation } from "react-router-dom";type LocationState = {  from: {    path: string;  }}const AuthLayer: React.FC = (props) => {  const location = useLocation();  const { from } = location.state as LocationState;  return <p></p>;};export default AuthLayer;

Also, remember to define the type, as per your requirements.For example, you might be using navigate(state.from).

For this Define the type as -

type LocationState = {  from : string;}