2017-04-12 82 views
1

我正在將Node + ES6項目轉換爲TypeScript。我瞄準ES6(因爲我正在運行Node 7.x)並使用Map。node + TypeScript:無法重新聲明塊範圍變量'events'

運行tsc -p回報:

  • src/actions.ts(3,9): error TS2451: Cannot redeclare block-scoped variable 'events'
  • src/calendar.ts(5,10): error TS2300: Duplicate identifier 'fetchEvents'.
  • src/index.ts(3,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'actions' must be of type 'Map<any, any>', but here has type 'any'.

目前尚不清楚爲什麼這些重複的標識或正在標記爲重新申報,特別是在上下文節點的需求/模塊導入。在require語句中使用標準const使得這個問題更加嚴重。

calendar.ts

const { rp } = require("request-promise") 

var events = <any> {} 

// both are exported via module.exports = { events, fetchEvents } 
function fetchEvents(key: string, url: string, options: object) { 
    ... 

actions.ts

const moment = require("moment") 
var { events, fetchEvents } = require("./calendar") 

var actions = new Map() 

tsconfig.json

{ 
    "compilerOptions": { 
    "target": "es6", 
    "outDir": "./built", 
    "declaration": true, 
    "rootDir": ".", 
    "baseUrl" : "./packages", 
    "experimentalDecorators": true, 
    "moduleResolution": "node", 
    "noImplicitAny": false, 
    "strictNullChecks": true, 
    "noImplicitReturns": true, 
    "noImplicitThis": true 
    }, 
    "include": [ 
    "src/**/*" 
    ], 
    "exclude": [ 
    "dist", 
    "node_modules", 
    ".vscode" 
    ] 
} 

回答

1

不知道var {...建設是有效的。 var使全局範圍變量作用域。

如果您在actions.ts使用:

const moment = require("moment") 
import calendar = require("./calendar"); 
// console.log(calendar.events) 

+0

這會起作用,因爲TypeScript似乎以不同的方式處理導入/名稱空間。我找不到有用的文檔,但是使用'module.exports = {events,fetchEvents}',然後導入爲'calendar'。 – elithrar