typescript namespace 和 interface有什么区别

现在我使用typescript 的 v2.1.5版本
使用webpack打包文件
之前已经装过依赖包和@types了

// 入口文件
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Router } from 'react-router';
import { Provider } from 'react-redux';
import { createBrowserHistory } from 'history';
import routes from './routes';
import configureStore from './store/configureStore';
ReactDOM.render(
  <Provider store={configureStore()}>
    <Router history={createBrowserHistory()}>
      { routes }
    </Router>
  </Provider>,
  document.getElementById('app')
);

但是我在编译的时候一直报history模块的一个错误:

[ts]
Type 'History' is not assignable to type 'History'. 
Two different types with this name exist, but they are unrelated.

我看了一下history/index.d.ts, 发现里面有多个export ... history, 如:

export as namespace History;

export interface History {
   ...
}

export namespace History {
   ...
}

createBrowserHistory.d.ts

import { History } from './index';
import { getConfirmation } from './DOMUtils';

export interface BrowserHistoryBuildOptions {
  basename?: string;
  forceRefresh?: boolean;
  getUserConfirmation?: typeof getConfirmation;
  keyLength?: number;
}

export default function createBrowserHistory(options?: BrowserHistoryBuildOptions): History;

我想知道这些这个问题怎么解决?怎样才能编译通过?

阅读 4.5k
1 个回答

简单方法:直接用react-routerbrowserHistory

题主没给出具体的版本,所有我按下面这个解释:

{
  "name": "segfault",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "history": "^4.5.0",
    "react-router": "^3.0.0"
  },
  "devDependencies": {
    "@types/history": "^4.5.0",
    "@types/react-router": "^3.0.0"
  }
}

第一个问题是@types/react-router里引用的@types/history的版本是^2devDependencies里的是^4.5.0,所有有了两个不同的History接口,而这两个History接口不兼容。

第二个问题是react-router里的history^3,和@types/react-router里的对不上。

解决方法就是直接用react-router里的browserHistory,也就是`^3"的版本。

或者去github提个issue了,把版本都改对了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题