小编Jim*_*eer的帖子

React TypeScript:react-router-dom 中 useLocation() 的正确类型

我正在努力为这种情况找到合适的类型。这是登录后重定向的简化版本。以下会产生编译器错误:

Property 'from' does not exist on type '{} | { from: { pathname: string; }; }'.
Run Code Online (Sandbox Code Playgroud)

添加修复编译器错误as any的使用,location.state但它很丑陋,并且 linter 会抱怨。

import React from "react";
import { useLocation } from "react-router-dom";

const AuthLayer: React.FC = (props) => {
  const location = useLocation();

  const { from } = location.state || { from: { pathname: "/" } };

  return <p></p>;
};

export default AuthLayer;
Run Code Online (Sandbox Code Playgroud)

typescript reactjs typescript-typings react-router-dom

10
推荐指数
3
解决办法
1万
查看次数