Search code examples
node.jstypescripttype-definition

How to write a type definition file for a default exported class?


I'm trying to write a type definition file for OpenSubtitles.org api node wrapper. Here is the main file index.js. On line 7 the OpenSubtitles class is exported as module's default export.

module.exports = class OpenSubtitles {
....
}

So i came up with the following

declare module "opensubtitles-api" {
  export default class OpenSubtitles {
  }
}

This is the transpilation of a code using OpenSubtitles.org api node wrapper and my .d.ts file.

"use strict";
exports.__esModule = true;
var opensubtitles_api_1 = require("opensubtitles-api");
var os = new opensubtitles_api_1["default"]({
    useragent: "TemporaryUserAgent"
});

and when i run it. I get this error.

var os = new opensubtitles_api_1["default"]({
         ^

TypeError: opensubtitles_api_1.default is not a constructor

When i remove the ["default"] part of the transpiled code everying work as expectd.

Desired transpilation

"use strict";
exports.__esModule = true;
var opensubtitles_api_1 = require("opensubtitles-api");
var os = new opensubtitles_api_1({
    useragent: "TemporaryUserAgent"
});

How should i export/declare OpenSubtitles class?


Solution

  • Default exports are different from when you are replacing the whole export object. The syntax for that is :

    declare module "opensubtitles-api" {
       class OpenSubtitles {
       }
       export = OpenSubtitles
    }