【问题标题】:declaration for a module that exports a self calling function导出自调用函数的模块的声明
【发布时间】:2017-02-09 02:23:55
【问题描述】:

这应该很简单,但我似乎无法弄清楚。 npm 模块 next-tick 在它的 index.js 中做了类似的事情:

module.exports = (function () {
    if (/*node*/) {
        return process.nextTick;
    }
    ...
    if (/*other env*/) {
        return function (cb) { setTimeout(callable(cb), 0); };
    }

    return null;
}());

还没有任何类型,所以我创建了 next-tick.d.ts 并将其包含在我的 tsconfig.js 中。

但是我不知道它应该包含什么:

我在没有编译器错误的情况下唯一可以工作的是:

declare module "next-tick" {
    export default function(fn:Function)
}

在消费文件中:

import nextTick from 'next-tick';

但是当我与 webpack 捆绑并运行它时,它会显示:next_tick_1.default is not a function。所以它试图打电话给.default

如果我使用 require(并使用 webpack 类型添加声明)也有效

var nextTick:(fn:Function)=>void = require('next-tick');

但我确定我应该能够通过 typescript 导入来做到这一点?

【问题讨论】:

    标签: typescript npm webpack typescript-typings


    【解决方案1】:

    试试这个

    declare module "next-tick" {
        function nextTick (fn:Function)
        export = nextTick
    }
    

    这使得函数被导出

    导入

    import nextTick = require('next-tick')
    

    不能使用 ES6 的 import 语法,因为这只是一个函数,而不是一个模块(ES6 要求)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-06
      • 2018-10-13
      • 1970-01-01
      • 2020-04-21
      • 2017-09-30
      相关资源
      最近更新 更多