【问题标题】:Typescript import from ES2015 export: how to specify type declaration file从 ES2015 导出的 Typescript 导入:如何指定类型声明文件
【发布时间】:2016-02-14 17:33:52
【问题描述】:

我正在尝试为 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(),因此无法运行。 (服务器.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);

【问题讨论】:

    标签: typescript ecmascript-6 feathersjs


    【解决方案1】:

    您正在为 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);
    

    【讨论】:

    • 知道了。谢谢你。我在 Typescript 规范 (11.3.5) 中发现了区别:“导出分配将模块成员指定为要导出的实体,而不是模块本身。”与 11.3.4.2 相比,它说“导出默认声明提供了用于导出名为 default 的实体的简写语法。”
    • stackoverflow.com/questions/29596714/… 的公认答案也值得一读。
    猜你喜欢
    • 2016-03-12
    • 2017-06-13
    • 2017-10-18
    • 2016-05-10
    • 2020-11-29
    • 2017-07-21
    • 2016-08-15
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多