【问题标题】:Create type definition for function returning the module itself为返回模块本身的函数创建类型定义
【发布时间】:2019-09-26 23:07:23
【问题描述】:

有一个nodejs模块是这样的

module.exports = {
  init(arg1) {
    // ..
    return this;
  },
  // ..
};

我正在尝试编写定义文件。看起来是这样的

declare namespace ModuleName {
  function init(smth: string): ModuleName;
}
export = ModuleName;
export as namespace ModuleName;
}

它几乎可以工作。当我导入它时

const a = require('ModuleName');

VSCode 理解 a.init 是一个接受一个字符串参数的函数。但我无法理解结果也有可以调用的方法init。即

const b = a.init('smth');
b.init('smth2');

在这种情况下编写类型定义的正确方法是什么?

【问题讨论】:

  • 你必须通过require而不是import来导入东西吗?

标签: typescript typescript-typings


【解决方案1】:

我发现只有通过接口的方法,但不确定。

declare namespace ModuleName {

    interface IModuleName {
        init(s: string): IModuleName;
    }

    function init(s: string): IModuleName;
}

const m = require('ModuleName');
const a = m.init('a');
const b = a.init('b');

或者更短

interface ModuleName {
    init(s: string): ModuleName;
}

const m: ModuleName = require('./ModuleName');
const a = m.init('a');
const b = a.init('b');

【讨论】:

  • 它似乎可以工作,但是该模块有大约 20 个嵌套函数、对象和类。应该有更好的方法......我希望。
  • 是的,我也希望如此。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-26
  • 1970-01-01
  • 2017-11-14
  • 2018-02-24
  • 1970-01-01
  • 2018-01-24
  • 2011-02-27
相关资源
最近更新 更多