For detailed information on how to work with 3rd party modules, take a look at the official documentation.
The way you write the declaration for a module depends on its structure and exports.
In the provided example, it's a CommonJS module (module.exports = ...
) which may not align perfectly with an ES6 module as ES6 does not support exporting a function directly as the module itself.
Update regarding TypeScript 2.7+
If you are using TypeScript version 2.7 or above, the addition of esModuleInterop
compiler option eliminates the need for certain hacks when dealing with non-ES6 compatible exports in CommonJS modules.
To leverage this feature, ensure that you have set esModuleInterop: true
in your tsconfig.json
file:
{
"compilerOptions" {
...
"esModuleInterop": true,
...
}
}
To declare a module like foo-example
, create a .d.ts
file with this format:
declare module "foo-module" {
function foo(): void;
export = foo;
}
You can then import it either as a namespace or as a default import.
Previous workaround
In case you are working with an older setup, you can still define a module like foo-example
in a .d.ts
file using a slightly different syntax:
declare module "foo-module" {
function foo(): void;
namespace foo { } // This hack enables ES6 wildcard imports
export = foo;
}
This allows you to import the module as you intended.
The official TypeScript documentation offers valuable insights into creating declaration files and provides templates for various types of declarations. Check out their resources on declaration files and templates for reference.