declare external libraries in the TypeScript file

Is there a way to define a third-party module that is structured like this:

Within the third-party module:

module.exports = function foo(){
  // perform an action
}

In my code:

import * as foo from 'foo-module'; // Unable to locate a declaration module for ...
foo();

Answer №1

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.

Answer №2

I encountered a similar issue and faced challenges while trying to add a type definition to my project. However, after much effort, I managed to solve it by following these steps.

Consider the module below (consisting of constants only), referred to as some-module - located at node_modules/some-module/index.js.

'use strict';

exports.__esModule = true;
var APPS = exports.APPS = {
    ona: 'ona',
    tacq: 'tacq',
    inetAcq: 'inetAcq'
};

Firstly, I included baseUrl and typeRoots in tsconfig.json

{
  ...
  "compilerOptions": {
    ...
    "baseUrl": "types",
    "typeRoots": ["types"]
  }
  ...
}

Next, within my project root directory, I created a folder named types with an identical folder structure to the module's typings in types/some-module/index.js, where I placed the following code:

declare module 'some-module' {
    type Apps =  {
        ona: string;
        tacq: string;
        inetAcq: string;
    };
    let APPS: Apps
}

Finally, I was able to import it into my my-file.ts file with proper typings!

import { APPS } from 'some-module';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing observable property in Angular 2 with TypeScript: A comprehensive guide

My observable is populated in the following manner: this._mySubscription = this._myService.fetchData(id) .subscribe( response => this._myData = response, ...

What is the best way to store objects containing extensive binary data along with additional values?

I'm currently working on saving a JavaScript object that includes binary data along with other values. I want the output to resemble the following: { "value":"xyz", "file1":"[FileContent]", "file2&quo ...

Using Angular 2 to trigger an event when a native DOM element is loaded

I am working towards my main objective of having a textarea element automatically focused upon creation. I recently came up with an idea to use e.target.focus() on the onload event. It would look something like this: <textarea rows="8" col="60" (load)= ...

Ways to integrate user input into the header of an Angular HTTP post method

I need help figuring out how to incorporate user input into the header of a post method I am working with. I understand that some kind of binding is necessary, but I'm struggling to implement it in this case. Currently, I have a variable called postDa ...

Having trouble retrieving cookie from UIWebview browser using the document.cookie method

In my iOS application, I am incorporating html content within a webview. This html is a login page where user credentials are sent to the server via ajax and an authentication success or failure response is received. The response includes a cookie in the S ...

Using Javascript to target elements with identical attributes

I have some HTML similar to the code below: <form name="test_form"> <input type="hidden" name="product_id" value="560"> <input type="hidden" name="product_name" value="test product"> <input type="hidden" name="product_type" value="7"& ...

Troubleshooting undefined results with AngularJS ng-repeat filter

My objective is to create a Letter Filter, where users can click on buttons from A to Z to filter the displayed data. When clicking on the letter 'A' button, only data starting with 'A' should be shown. However, I have encountered an i ...

Utilizing Object Assign to reset the state

Here lies the declaration of my current state: export default new Vuex.Store({ state: { items: [ ], user: { isAuthenticated: false, info: { createdAt: '', email: '', firstName: '&a ...

There was a TypeError encountered when attempting to read the length property of a null value in the Google Map JSON data

I keep getting an Uncaught TypeError: Cannot read property 'length' of null error when I attempt to use JSON data as markers on my Google map. However, when I check console.log(data);, it shows that the data is fine. What could be causing this is ...

Error message: "Unassigned value in knockout.js"

Here is my code snippet for binding to a textbox: var CategoryViewModel = { categoryModel: ko.observable({ categoryId: ko.observable(), categoryName: ko.observable(), active: ko.observable() }), GetCategoryById: functio ...

Is there a way to create a dictionary in Javascript with all keys pointing to the same value?

I have a scenario where I need to convert an array into an object like this: let arr = ['ABC', 'DEF'] The desired transformation is: let obj = {"ABC": 0, "DEF": 0} Can someone guide me on how to achieve this using ...

Difficulty transferring form information to PHP utilizing Ajax

Originally, I had a traditional HTML form that submitted data through a button, redirecting the user to the page where the PHP code ran successfully. Now that everything is functioning as expected, I aim to pass the form variables to PHP using Ajax in ord ...

Turn off spellcheck for all material-ui elements

Is there a way to deactivate spellcheck globally for elements in the material-ui library? Before incorporating the material-ui library into my project, I used the code below to turn off spellcheck for all new DOM elements: const disableSpellCheck = funct ...

How can I trigger a JavaScript function when the ENTER key is pressed?

I'm attempting to use JavaScript to scroll down a page. The code below works perfectly when I use javascript:pageScroll() in a link or button: <SCRIPT LANGUAGE="Javascript"> function pageScroll() { window.scrollBy(0,50); // hor ...

What is the reason behind the specific sequence in which this JavaScript console log is displayed?

Extracted from Chapter 11 of the book Eloquent Javascript, this code snippet showcases the use of Promises. You can interact with the code in a sandbox environment here. I recently dabbled with the Promises featured in this snippet and was surprised to fin ...

Obtaining and transferring identifiers for jQuery code execution

My goal is to create a script that dynamically changes the content of a webpage using a foreach array. The HTML structure I am working with looks like this: <div id="bigleftproject"> <p>content to be replaced</p> </div> <div ...

Verify the checkbox for validation is shown exclusively

I am currently facing an issue with a form that includes a checkbox, which is only displayed under certain conditions. I want to ensure that the checkbox is checked only when it is visible, and if not, the form should be submitted upon clicking the submit ...

Is there a way to use HTML, JavaScript, and CSS to manipulate an object's opacity when a button is clicked?

I am looking to add a button on my website landing page that can hide the weather section, but I am unsure how to go about it! https://i.sstatic.net/COA82.jpg Currently, I am using a "selector" where I can choose either 0 or 1 from the bottom right corner ...

Enhance cart items in a shopping cart using Redux

I'm encountering an issue with my reducer's functionality in adding an item to the cart and increasing its quantity if it already exists. Currently, instead of updating the existing quantity, my code simply adds another "quantity" with a value of ...

Simultaneously opening the second submenu and closing the previous submenu with a height transition results in the second submenu being positioned off-screen

Sample: https://codesandbox.io/p/sandbox/navbar-k2szsq (or refer to the code snippet below) In my navbar, I have implemented multiple submenus with a height transition when the user opens or closes a submenu. However, only one submenu can be open at a tim ...