How do I write a TypeScript declaration file for a complex external commonjs module that has constructor, such as imap?

前端 未结 2 1847
一向
一向 2021-01-25 12:09

This question is a refinement of my earlier one: How do I write a TypeScript declaration file for an external commonjs module that has constructor?

I\'m trying to write

2条回答
  •  清酒与你
    2021-01-25 12:44

    After continuing to investigate this problem, I have written the definition file, but still haven't found a way to put all of the interfaces inside of the module, to avoid pollution of the global scope.

    I submitted the definition file in a pull request to DefinitelyTyped, and you can view it here: https://github.com/psnider/DefinitelyTyped/commit/460bb6d63e349918b20e49d7a62f3d2a7c2aea0a


    EDITED

    Thanks, basarat, for pointing me in the right direction, although I was unable to sew it together until I found a few more missing pieces.

    I reviewed other answers and definition files and found a method that appears to work, and have updated my pull request: https://github.com/borisyankov/DefinitelyTyped/pull/3324

    I used this pattern in imap.d.ts:

    declare module IMAP {
        export interface Config {}
        export class Connection {
            constructor(config : Config);
        }
    }
    declare module "imap" {
        var out: IMAP.Connection;
        export = out;
    }
    

    Where IMAP is a non-initializaed module, as basarat suggested, and it makes the interfaces accessible within the IMAP namespace.

    Then in the code that uses the imap module, example.ts:

    ///    // brings module IMAP into scope
    import Imap = require('imap');       // gets the connection class
    var conn = new Imap({/* omitted for brevity*/});  // creates an imap connection
    

提交回复
热议问题