如何为导出函数的commonjs模块编写定义文件

Ale*_*jic 5 commonjs typescript typescript-typings typescript2.0

我想在typescript中使用简单的commonjs模块,这里有3个文件

原始的lib:

//commonjs-export-function.js
module.exports = function() {
    return 'func';
};
Run Code Online (Sandbox Code Playgroud)

定义文件:

//commonjs-export-function.d.ts
declare function func(): string;
export = func;
Run Code Online (Sandbox Code Playgroud)

使用它的打字稿程序:

//main.ts
import { func } from './commonjs-function';

console.log(func());
Run Code Online (Sandbox Code Playgroud)

当我运行tsc时,我收到此错误:

tsc main.ts && node main.js
main.ts(1,22): error TS2497: Module '"/Users/aleksandar/projects/typescript-playground/commonjs-function"' resolves to a non-module entity and cannot be imported using this construct.
Run Code Online (Sandbox Code Playgroud)

这里也已经回答了问题,但它不适用于typescript 2.0

如何为导出函数的节点模块编写打字稿定义文件?

Ale*_*jic 6

我在这里找到了打字稿文档中的解决方案:http://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-function-d-ts.html

*~ Note that ES6 modules cannot directly export callable functions.
*~ This file should be imported using the CommonJS-style:
*~   import x = require('someLibrary');
...
export = MyFunction;
declare function MyFunction(): string;
Run Code Online (Sandbox Code Playgroud)

所以mu定义文件应该是:

//commonjs-export-function.d.ts
declare function func(): string;
export = func;
Run Code Online (Sandbox Code Playgroud)

并使用require导入:

//main.ts
import func = require('./commonjs-export-function');
Run Code Online (Sandbox Code Playgroud)