typescript - 使用 @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;
解决方案
您的问题根本不在于@types/history
图书馆。这typedef
是在您的设置中配置规则以要求在包括变量tslint.json
在内的地方进行类型定义。history
此代码可能还会显示 TSLint 投诉:
const createMyHistory = () => ({
someMember: "someValue",
});
const history = createMyHistory();
..history
因为没有明确的类型定义。
这里有两种方法可以在没有 的情况下解决错误// tslint:disable-next-line
:
禁用或以其他方式配置
typedef
规则以停止抱怨这种情况:请参阅https://palantir.github.io/tslint/rules/typedef/和https://palantir.github.io/tslint/usage/configuration。这可能最终成为您的一部分tslint.json
:{ "rules": { "typedef": false } }
向
history
变量添加显式类型定义:const history: History = createBrowserHistory();
编辑:只是为了增加对下面评论中的内容的可见性,这里有两种类型/接口History
在起作用。一种是 DOM 类型附带的全局定义的。另一个是在 中定义的@types/history
。不幸的是,它们都具有相同的名称,这令人困惑。如果您看到与History<any>
不兼容的错误History
,请添加History
到您的import
from history
:
import { createBrowserHistory, History } from 'history';
这将使您的代码引用@types/history
的版本。
推荐阅读
- django - 如何修复 django 中的错误凭据错误
- c# - 如何使用闭包从发出的方法调用 DynamicMethod
- javascript - 有条件地将类应用于列表中的特定项目 Vue.js 3.0
- java - 使用 JWT 授权微服务
- sql - 如何在嵌套的双美元符号交叉表查询中使用 postgres 参数
- scala - Scala 和 playframework 在节点之间共享缓存
- javascript - 如何将 axios 包添加到我正在处理的 chrome 扩展中?
- javascript - 在 HTML 中编辑 SRC
- python - 将更正应用于数据帧的子采样副本回到原始数据帧?
- python - 如何创建一个 for 循环来生成 1110 个值的范围?