How to declare a third-party module in TypeScript?
I am trying to use a third-party module that is structured like this:
In the third-party module:
module.exports = function foo(){
// do something
}
In my TypeScript code:
import * as foo from 'foo-module'; // Error: Cannot find a declaration module for ...
foo();
How can I properly declare the third-party module in TypeScript to resolve this issue using typescript declare module
?
I’ve dealt with this kind of issue before, and a straightforward way to resolve it is by using a global declaration. If the third-party module doesn’t have any type definitions, you can inform TypeScript that it exists by creating a declaration file. Here’s how you can do it:
// Create a custom type declaration file (e.g., `foo-module.d.ts`)
declare module 'foo-module' {
export default function foo(): void;
}
// In your TypeScript code
import foo from 'foo-module';
foo();
This approach essentially tells TypeScript that the module exists and exports a default function. It’s simple and works great if the module is structured to export a default function.
That’s a solid start, Emma! Another way you can handle this, particularly if the module uses module.exports
, is by declaring the module in a way that aligns with the CommonJS structure.
// Create a custom type declaration file (e.g., `foo-module.d.ts`)
declare module 'foo-module' {
const foo: () => void;
export = foo;
}
// In your TypeScript code
import * as foo from 'foo-module';
foo();
This approach uses export =
to match the module.exports
pattern. It’s handy when the third-party module doesn’t follow ES modules and instead uses CommonJS. This method is a bit more specific and works well when you know the module’s export structure follows module.exports
.
Great insights so far! Building on that, another flexible option—especially when you’re working with CommonJS modules and prefer require
—is to use typescript declare module
while leveraging require()
. Here’s how:
// Create a custom type declaration file (e.g., `foo-module.d.ts`)
declare module 'foo-module' {
const foo: () => void;
export = foo;
}
// In your TypeScript code
const foo = require('foo-module');
foo();
This method ensures compatibility with CommonJS modules and keeps things consistent if your project or coding style leans toward using require()
for imports. It’s particularly useful in legacy systems where ES modules aren’t fully embraced.