是否有可能在打字稿中使用nodejs风格的模块?

在节点中,我可以通过设置exports对象的属性来定义一个这样的模块:

module.js

 exports.fun = function (val) { console.log(val); }; 

并使用var module = require('module')来请求它并使用module.fun()函数。

是否可以像这样在TypeScript中定义模块:

module.ts

 exports.fun = function (val :string) { console.log(val); }; 

然后使用类似语法的节点(比如import module = require('module.ts')将其导入到其他某个文件中,以便将其编译为nodejs,但是如果现在在某些.ts文件中使用module.fun()它应该给我一个错误,如果参数不符合module.ts文件中指定的types。

我怎样才能在打字稿中做到这一点?

你已经基本描述了TypeScript中的外部模块是如何工作的。

例如:

Animals.ts

 export class Animal { constructor(public name: string) { } } export function somethingElse() { /* etc */ } 

Zoo.ts

 import a = require('./Animals'); var lion = new a.Animal('Lion'); // Typechecked console.log(lion.name); 

使用--module commonjs编译并在节点中运行zoo.js。

是的,可以使用真正的js语法。 由于您正在使用import关键字(您希望导入的文件使用export关键字),因此您将收到错误消息。 如果你想要js的exports.foo语法,你应该使用var而不是import。 以下将编译/工作得很好:

 var module = require('module.ts')