【问题标题】:Tslint error when using createBrowserHistory() from @types/history使用 @types/history 中的 createBrowserHistory() 时出现 Tslint 错误
【发布时间】:2019-06-27 05:16:53
【问题描述】:

我在我的 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 */ 来删除 tslint 规则。我想添加类型支持,然后修复它。

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;

【问题讨论】:

    标签: typescript tslint


    【解决方案1】:

    您的问题根本不在于 @types/history 库。就是typedef 规则在您的tslint.json 设置中配置为要求在包括history 变量在内的位置进行类型定义。

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

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

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

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

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

    import { createBrowserHistory, History } from 'history';
    

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

    【讨论】:

    • 当我向历史变量添加显式类型定义时,正如您在最后一行中建议的那样,我收到此编译时错误。 [ts] 类型 'History' 不可分配给类型 'History'。 “历史”类型中缺少属性“scrollRestoration”。
    • 诡异。可能有两种类型在起作用:一种是预定义的全局History,另一种是@types/history 定义中的类型,它也恰好被命名为History。他们如何命名相同的东西有点不方便。如果您从historyHistory 添加到您的import,投诉会消失吗?
    猜你喜欢
    • 2022-11-23
    • 2019-08-23
    • 2018-09-06
    • 2020-11-16
    • 2018-04-12
    • 2018-04-25
    • 1970-01-01
    • 2018-06-20
    • 2021-05-20
    相关资源
    最近更新 更多