查看documentation on working with 3rd party modules。
如何编写声明很大程度上取决于模块的编写方式和导出的内容。
您给出的示例是一个 CommonJS 模块 (module.exports = ...),它不是真正有效的 ES6 模块,因为 ES6 无法导出函数作为模块(它只能导出函数成员或 default 函数)。
TypeScript 2.7+ 更新
添加 esModuleInterop compiler option 后,对于具有非 ES6 兼容导出的 CommonJS 模块,您不再需要使用下面显示的“命名空间破解”。
首先,确保您在tsconfig.json 中启用了esModuleInterop(现在默认情况下包含在tsc --init 中):
{
"compilerOptions" {
...
"esModuleInterop": true,
...
}
}
在.d.ts 文件中声明您的foo-example,如下所示:
declare module "foo-module" {
function foo(): void;
export = foo;
}
现在您可以将其作为您想要的命名空间导入:
import * as foo from "foo-module";
foo();
或作为默认导入:
import foo from "foo-module";
foo();
较旧的解决方法
您可以像这样在.d.ts 文件中声明您的foo-example:
declare module "foo-module" {
function foo(): void;
namespace foo { } // This is a hack to allow ES6 wildcard imports
export = foo;
}
并按您的意愿导入:
import * as foo from "foo-module";
foo();
或者像这样:
import foo = require("foo-module");
foo();
documentation has a good resource on declaration files 和一些templates for various kinds of declaration files。