如何在声明文件的命名空间中键入循环引用?

时间:2019-10-02 05:11:29

标签: typescript definitelytyped .d.ts

我正在尝试为DefinitelyTyped项目键入一个UMD模块(我不拥有它,因此无法更改它)(具有实际功能):

function getModule() {
    function fn1() {}
    function fn2() {}

    fn1.fn2 = fn2;
    return fn1.fn1 = fn1;
}

if (typeof define === "function" && define.amd) {
    define(getModule());
} else if (typeof module !== "undefined" && module.exports) { 
    module.exports = getModule();
} else {
    this.moduleName = getModule();
}

到目前为止,我使用the module-function.d.ts模板:

export as namespace moduleName;

export = fn1;

declare function fn1(): void;

declare namespace fn1 {
    function fn2(): void;
}

然后我使用dts-gen生成了一个.d.ts文件,以尝试找出如何在fn1命名空间中再次声明fn1函数,并得到了以下信息: / p>

/** Declaration file generated by dts-gen */

export = moduleName;

declare function moduleName(): void;

declare namespace moduleName {
    // Circular reference from moduleName
    const fn1: any;

    function fn2(): void;
}

但是,当我尝试在以下代码中将两者结合时,出现错误'fn1' is referenced directly or indirectly in its own type annotation.

export as namespace moduleName;

export = fn1;

declare function fn1(): void;

declare namespace fn1 {
    function fn2(): void;
    const fn1: any;
}

我不想执行以下操作,因为那样做并不代表您可以执行require('moduleName').fn1.fn1.fn1.fn2(或任意数量的fn1 s。

export = moduleName;

declare function moduleName(): void;

declare namespace moduleName {
    function fn1(): void;
    function fn2(): void;
}

我将如何键入该模块?

1 个答案:

答案 0 :(得分:0)

您可以使用界面来准确表示递归类型:

export = fn1;

declare const fn1: Fn1

interface Fn1 {
  // The call signature of fn1
  (): void
  // The circular reference
  fn1: Fn1
  // Other functions
  fn2: () => void
}