0

我正在尝试为 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) 中获得了所有不错的类型检查帮助。.default()Typescript 编译为以下 ES5,由于默认导出的结果而无法运行。(服务器.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";

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

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

打字稿编译器错误是:

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);
4

1 回答 1

0

您正在为 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);
于 2016-02-15T08:32:24.883 回答