如何修复 Typescript 中的 'Property "string" does not exist on type "object"' 错误
How To fix 'Property "string" does not exist on type "object"' error in 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'.
为什么我的代码不正确?
如另一个答案中所述,withRouter
必须从 react-router
导入。
但要回答关于 Typescript 错误的问题,这是因为 location
已被定义为 typescript 的 object
而未指定其属性。这就是为什么当您尝试访问 pathname
时出现错误的原因。
幸运的是,您不必在 location prop 上写出所有属性。相反,您可以使用以下命令安装 react-router 类型:
npm install --save @types/react-router @types/react-router-dom
在创建继承这些属性(匹配、位置、历史)的组件时,只需扩展 RouteComponentProps
:
import { RouteComponentProps } from "react-router";
interface IProps extends RouteComponentProps {
// other props
}
我正在尝试使用带有以下代码的 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'.
为什么我的代码不正确?
如另一个答案中所述,withRouter
必须从 react-router
导入。
但要回答关于 Typescript 错误的问题,这是因为 location
已被定义为 typescript 的 object
而未指定其属性。这就是为什么当您尝试访问 pathname
时出现错误的原因。
幸运的是,您不必在 location prop 上写出所有属性。相反,您可以使用以下命令安装 react-router 类型:
npm install --save @types/react-router @types/react-router-dom
在创建继承这些属性(匹配、位置、历史)的组件时,只需扩展 RouteComponentProps
:
import { RouteComponentProps } from "react-router";
interface IProps extends RouteComponentProps {
// other props
}