TypeScript Declaration File (Function Constructor)

Viewed 440

I am trying to create a TypeScript Declaration file for an npm package.

JavaScript (index.js from npm package):

function Foo(config = {}) {
   this.configuration = {
       prop1 = config.prop1 || 'value'
   }
}
/// more...
module.exports = Foo;

My TypeScript Declaration File (index.d.ts):

declare module '@company/modulename' {

   interface config {
      prop1?: string;
   }

   declare function Foo(config: config): void;
   exports = Foo;
}

Usage (server.ts):

import { Foo } from '@company/modulename'; // <-- this fails as noted below
// const Foo = require('@company/modulename'); <-- this works!

const foo = new Foo({
   prop1: 'Halp'
});

/// more stuff...

Problem:

The TypeScript Declaration file is very helpful. EXCEPT, when I try to run server.ts, I get an error: TypeError: modulename_1.Foo is not a constructor. If I switch to the require syntax, everything works as expected... but then I don't get the type checking!

My tsconfig.json:

{
  "compilerOptions": {

    "target": "ES2019",                          
    "module": "commonjs",                     
    "outDir": "dist",                         
    "rootDir": "./",                          

    /* Strict Type-Checking Options */
    "strict": true,
    "noImplicitAny": false,                                     

    /* Additional Checks */

    /* Module Resolution Options */
    "esModuleInterop": true,                  

    /* Source Map Options */

    /* Experimental Options */

    /* Advanced Options */
    "skipLibCheck": true,                     
    "forceConsistentCasingInFileNames": true  
  }
}

UPDATED + CORRECTED:

My TypeScript Declaration File (index.d.ts):

declare module '@company/modulename' {

   interface config {
      prop1?: string;
   }

   export default function Foo(config: config): void;
}

Usage (server.ts):

import Foo from '@company/modulename'; // Braces removed from Foo

const foo = new Foo({
   prop1: 'Halp'
});
1 Answers

Does import Foo from '@company/modulename'; not work? if not try, export default Foo;, then try again.

Related