首页 > 解决方案 > 使用 @types/history 中的 createBrowserHistory() 时出现 Tslint 错误

问题描述

我在我的 React 应用程序中导入@types/history并使用它提供的功能。createBrowserHistory()

我收到一个 tslint 错误说,

ERROR in C:/Users/eshan/my-website/src/App.tsx
ERROR in C:/Users/eshan/my-website/src/App.tsx(13,11):
typedef: expected variable-declaration: 'history' to have a typedef

我确实环顾了一下,但所有减轻这种情况的尝试似乎都是为了通过/* tslint:disable */. 我想添加类型支持,然后修复它。

import * as React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import './App.css';

class App extends React.Component {
  public render(): JSX.Element {
  const history = createBrowserHistory();

  return (
    <div className='App'>
      <Router history={history}>
        <Switch>
          <Route exact path='/' component={Landing}/>
          <Route exact path='/Home' component={Home}/>
        </Switch>
      </Router>
    </div>
    );
  }
}

export default App;

标签: typescripttslint

解决方案


您的问题根本不在于@types/history图书馆。这typedef是在您的设置中配置规则以要求在包括变量tslint.json在内的地方进行类型定义。history

此代码可能还会显示 TSLint 投诉:

const createMyHistory = () => ({
    someMember: "someValue",
});

const history = createMyHistory();

..history因为没有明确的类型定义。

这里有两种方法可以在没有 的情况下解决错误// tslint:disable-next-line

编辑:只是为了增加对下面评论中的内容的可见性,这里有两种类型/接口History在起作用。一种是 DOM 类型附带的全局定义的。另一个是在 中定义的@types/history。不幸的是,它们都具有相同的名称,这令人困惑。如果您看到与History<any>不兼容的错误History,请添加History到您的importfrom history

import { createBrowserHistory, History } from 'history';

这将使您的代码引用@types/history的版本。


推荐阅读