Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export entire module as constructor

Tags:

typescript

Say I have a nodejs module that, when I require it, it returns a constructor function to me. Something like the following:

var Mod = require("modulename");
var mod = new Mod();
mod.method();

I want to write a .d.ts declaration file that can be imported and used like so:

import * as Mod from "mod";
let mod = new Mod();
mod.method();

I've tried reading all the documentation on the Typescript website but it's honestly as clear as mud, and I feel like I've tried every combination of class, interface, namespace, module and export that exists in my .d.ts file. I'm wondering if the above is even achievable. Can anybody offer any help?

like image 851
Hy- Avatar asked Dec 06 '25 07:12

Hy-


1 Answers

Instead of writing this

import * as Mod from "mod";
let mod = new Mod();

You should write this

import Mod = require("mod");
let mod = new Mod();

Why?

import * as Mod from "mod";

This is ES6 module import syntax. It says you're importing the "mod" module object into the local name Mod. ES6 modules only expose properties, and cannot be invoked as a function or with new.

I'll say this again because people often don't believe me or choose to ignore it: ES6 modules only expose properties, and cannot be invoked as a function or with new.

If you start compiling your code to an ES6 runtime (instead of downleveling to ES5 modules with CJS / AMD), your code will stop working. There's no require function in ES6 modules, though, so the "old-style" import Mod = require("mod"); is still OK.

like image 75
Ryan Cavanaugh Avatar answered Dec 07 '25 21:12

Ryan Cavanaugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!