NodeJS,TypeScript和typescript集合
我想从NodeJS中的typescript集合中使用Dictionary类:
/// <reference path="../../../scripts/collections.ts" /> var collections = require('../../../scripts/collections'); export class AsyncProcessorCommand implements interfaces.IAsyncProcessorCommand { public static Type = 'RabbitMon.AsyncProcessorCommand:RabbitMon'; public GetType = () => 'RabbitMon.AsyncProcessorCommand:RabbitMon'; public ID: string; constructor(public Action: string, public Arguments?: collections.Dictionary<string, string>) { this.ID = uuid.v4(); this.Arguments = new collections.Dictionary<string, string>(); //I've also tried the following //this.Arguments = new collections.Dictionary<string, string>((key: string) => sha1(key)); } }
但是我不断收到new Dictionary
上的以下错误:
TypeError: undefined is not a function
任何人都知道这里发生了什么? 我也非常乐意替代一个更好的工作TScollections库…
你有一个内部VS外部模块问题。
TypeScript集合库被编写为一个内部模块 – 一个标准的JavaScript文件,您可以将其放入网页的script
标记中。
然而,节点的require
,期望一个CommonJS兼容的文件,将分配的东西exports
,换句话说外部模块 。 发生了什么事情是node.jsfind了collections.js
,执行它,并从评估文件返回exports
对象。 因为它只是一个普通的JS文件,导出的对象是空的。
最好的解决办法是:
- 把你的引用
collections.ts
replace为collections.d.ts
,只是为了正确(运行tsc --d collection.ts
来生成这个文件) - 使用一些解决scheme在节点中加载“vanilla”JS文件。
eval(require('fs').readFileSync('./path/to/file.js', 'utf8'));