首页 > 解决方案 > 如何修复 Typescript 中的“对象”类型上不存在“属性“字符串”错误

问题描述

我正在尝试使用带有以下代码的 Typescript 在 React Router 中实现Scroll Restoration 。

import { Component } from 'react';

import { withRouter } from "react-router-dom";

export interface IProps {
  prevProps?: any;
  location: object;
  pathname?: any;
}

class ScrollToTop extends Component<IProps, object> {

  componentDidUpdate(prevProps?: any) {
    if (this.props.location.pathname !== prevProps.location.pathname) {
      window.scrollTo(0, 0);
    }
  }

  render() {

    return this.props.children;

  }

}

export default withRouter(ScrollToTop);

但是,当我添加位置和路径名的类型时,我继续收到以下 TS 错误。

(14,29): Property 'pathname' does not exist on type 'object'.

为什么我的代码不正确?

标签: reactjstypescriptreact-router-dom

解决方案


如另一个答案中所述,withRouter必须从react-router.

但是要回答您关于 Typescript 错误的问题,这是因为location已将其定义为objectfor typescript 而没有在其上指定属性。这就是为什么当您尝试访问pathname它时出现错误的原因。

幸运的是,您不必在 location 属性上写出所有属性。相反,您可以安装 react-router 类型:

npm install --save @types/react-router @types/react-router-dom

创建继承这些道具(匹配、位置、历史)的组件时,只需扩展RouteComponentProps

import { RouteComponentProps } from "react-router";

interface IProps extends RouteComponentProps {
  // other props
}

推荐阅读