从ES2015导出的Typescript导入:如何指定类型声明文件

时间:2016-02-14 17:33:52

标签: typescript ecmascript-6 feathersjs

我试图为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语句更改为:

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

1 个答案:

答案 0 :(得分: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);