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

前端 未结 2 1848
一向
一向 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:39

    Ideally, all of the interfaces will be defined inside of module "imap", so there is no pollution of the global scope

    Instead of:

    interface IFetchOptions {
        markSeen:       boolean;
        // so on
    }
    interface ICriteria {        
        ALL:            void;
    }
    

    Do the following

    module imap {
        interface IFetchOptions {
            markSeen:       boolean;
            // so on
        }
        interface ICriteria {        
            ALL:            void;
        }
    }
    

    And you only pollute the global scope with imap. Which is a non-initializaed module and can only be used for Type Information.

    Reference : look at ghost modules : http://definitelytyped.org/guides/best-practices.html

    0 讨论(0)
  • 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:

    /// <reference path='imap.d.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
    
    0 讨论(0)
提交回复
热议问题