title: How do I write a TypeScript declaration file for an external commonjs module that has constructor?
body: <p>PLEASE SEE MORE DETAILED QUESTION: <a href="https://stackoverflow.com/questions/26249210/how-do-i-write-a-typescript-declaration-file-for-a-complex-external-commonjs-mod">How do I write a TypeScript declaration file for a complex external commonjs module that has constructor, such as imap?</a></p>
  
  <p>I write TypeScript for a Node.js app, and I want to write a TypeScript declaration file for a javascript module (available from npm) that has a constructor at the module level.</p>
  
  <p>Here is a simplified version of the relevant code, in file <strong>a.js</strong>:</p>
  
  <pre><code>function A(config) {
      this.state = 'constructed';
  }
  A.prototype.update = function() {
      this.state = 'updated';
  };
  module.exports = A;
  </code></pre>
  
  <p>and a simplified javascript application, <strong>app.js</strong>, that uses module <strong>a</strong>:</p>
  
  <pre><code>var mod = require('a');
  var i = new mod({});
  console.log('i.state=' + i.state);
  i.update();
  console.log('i.state=' + i.state);
  </code></pre>
  
  <p>How do I write a TypeScript declaration file for module <strong>a.js</strong>?</p>
  
  <p>I've read the <a href="https://typescript.codeplex.com/wikipage?title=Writing%20Definition%20%28.d.ts%29%20Files" rel="nofollow noreferrer">TypeScript Guide for Writing Definition (.d.ts) Files</a>
  but unfortunately, I couldn't figure out how to apply the guidelines to this case.</p>
  
  <hr>
  
  <h2>updated to include interfaces</h2>
  
  <p>Here is my declaration file <strong>a.d.ts</strong>:</p>
  
  <pre><code>declare module 'a' {
      import events                           = require('events');
      import EventEmitter                     = events.EventEmitter;
  
      interface Config {
          foo: number;
      }
      interface Other {
          baz: number;
      }
  
      class A extends EventEmitter {
          state: string;
          constructor(config: Config);
          update(): void;
      }
  
      var out: typeof A;
      export = out;
  }
  </code></pre>
  
  <p>I can't figure out how to make the interfaces available to my TypeScript app. 
  I also want to keep them within the module, so that names like Config don't collide with those from other modules.</p>
  
  <hr>
  
  <h2>Added TypeScript app that uses this declaration</h2>
  
  <p>This is what I expect my <strong>app.ts</strong> to look like:</p>
  
  <pre><code>import mod = require('a');
  import Config = mod.Config;
  import Other = mod.Other;
  
  var other : Other = {a: 2};
  var config : Config = {foo: 2};
  var i = new mod(config);
  console.log('i.state=' + i.state)
  i.update();
  console.log('i.state=' + i.state)
  </code></pre>