Search code examples
javascriptnode.jstypescriptcommonjstypescript-typings

TypeScript definition file for existing node module


In my TypeScript project I want to use Logdown.

Logdown can be used in a Node.js application like this:

var Logdown = require('logdown')
var logger = new Logdown({prefix: 'test'})
logger.info('Hello World');

Unfortunately, Logdown does not provide declarations, so I wanted to write a declaration file.

To kickstart this little project, I did the following:

  • I cloned the Logdown repository
  • I created a "typings" entry in the package.json file of the cloned Logdown repository and pointed it do dist/logdown.d.ts (according to "Including declarations in your npm package")
  • I made the cloned Logdown repository locally available as npm package (npm link)
  • I ran npm link logdown within my TypeScript application to point this Node module reference to my cloned repository

After that I created the content for the logdown.d.ts file:

export declare class Logdown {
  constructor(options: Object);
  public info(text: string): string;
}

I was hoping that I can use now Logdown in my TypeScript project like this:

import Logdown = require("logdown");
let logger: Logdown = new Logdown();
logger.info('Hello World!');

But when I compile the project, I get the following errors:

error TS2304: Cannot find name 'Logdown'.

error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.


Solution

  • I got it working: I needed to change the export format to export = Logdown; in the definition file (.d.ts) and the import format to import Logdown = require("logdown"); in my TypeScript application.

    Logdown.d.ts (Export Definition)

    declare class Logdown {
      constructor(options?: Object);
      public log(...args: string[]): void;
      public info(...args: string[]): void;
      public warn(...args: string[]): void;
      public debug(...args: string[]): void;
      public error(...args: string[]): void;
      public static disable(...args: string[]): void;
      public static enable(...args: string[]): void;
    }
    
    export = Logdown;
    

    TypeScript Application (Import)

    import Logdown = require("logdown");
    ...
    let logger: Logdown = new Logdown();
    logger.info('Hello from Logdown!');