Benny Code
Benny Code

Reputation: 54995

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:

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.

Upvotes: 2

Views: 1048

Answers (1)

Benny Code
Benny Code

Reputation: 54995

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!');

Upvotes: 5

Related Questions