Typescript import from ES2015 export:如何指定类型声明文件

Typescript import from ES2015 export: how to specify type declaration file

我正在尝试为 feathersjs 制作一个稀疏类型声明文件,以便我可以更好地在 Typescript 中使用它。

Feathers 使用 ES2015 编写并分发 ES5(通过 Babel)。 ES5 默认导出:

function createApplication() {
  var app = express();
  Proto.mixin(Application, app);
  app.init();
  return app;
}
module.exports = createApplication;

我的类型声明文件(feathers.d.ts):

declare module "feathers" {
    import * as express from "express";
    import * as serveStatic from 'serve-static';

    interface Feathers extends express.Express {
        (func?: express.Express): Feathers;
        setup(): Feathers;
        static: typeof serveStatic;
    }

    var createApplication: Feathers;

    export default createApplication;
}

我的应用程序(server.ts):

import feathers from "feathers";
const app = feathers();
app.use('/', feathers.static(__dirname)).listen(3001);

到目前为止,typescript 编译没有错误,我在 IDE (atom-typescript) 中获得了所有不错的类型检查帮助。 Typescript 编译为以下 ES5,它不会 运行 因为默认导出导致 .default()。 (server.js):

var feathers_1 = require("feathers");
var app = feathers_1.default();
app.use('/', feathers_1.default.static(__dirname)).listen(3001);

如果我将导入语句更改为:

import * as feathers from "feathers";

然后类型检查失败并且编译器发出错误,但它确实产生 运行ning ES5:

var feathers = require("feathers");
var app = feathers();
app.use('/', feathers.static(__dirname)).listen(3001);

typescript 编译器错误是:

error TS2349: Cannot invoke an expression whose type lacks a call signature.
error TS2339: Property 'static' does not exist on type 'typeof "feathers"'.

问题:在这种情况下,应该使用以下哪个import语句?或者,声明文件(上面列出的)有什么问题?

// import feathers from "feathers"; // no errors, but emits .default object
// import * as feathers from "feathers"; // errors, but working ES5
// import feathers = require("feathers"); // errors, but working ES5
const app = feathers();
app.use('/', feathers.static(__dirname)).listen(3001);

您正在为 CommonJS 模块编写类型,所以不要使用 export default,而是这样做:

declare module "feathers" {
  // ...

  var createApplication: Feathers;
  export = createApplication;
}

然后像这样导入:

import feathers = require('feathers');
// OR
import * as feathers from 'feathers';

const app = feathers();
app.use('/', feathers.static(__dirname)).listen(3001);