The announcement will not be made as a result of the utilization of a private name

I've been working on transitioning a project to TypeScript, and while most of the setup is done, I'm struggling with the final steps. My goal is to use this TypeScript project in a regular JavaScript project, so I understand that I need to generate d.ts files for my existing sources. Currently, all my sources are .js files, and we are planning a gradual migration to TS. The challenge lies in emitting declarations alongside the current exports/require statements.

Here's a simple example illustrating the issue:

mod1.js

class MyClass {
        constructor(name) {
            this.name = name;
        }
    }

    module.exports = {
        MyClass,
    };
    

mod2.js

const mod1 = require('./mod1');

    module.exports = {
        MyClass: mod1.MyClass,
    };
    

When attempting to export MyClass in mod2 to redirect the namespace from which one can access MyClass when consuming the project, I encounter

Declaration emit for this file requires using private name 'MyClass' from module '"mod1"'. An explicit type annotation may unblock declaration emit.ts(9006)

We have numerous redirects in our codebase, with sets of files containing various classes, and index.js files at each directory level defining the available items in that namespace. We also have UI elements instantiated as class instances allowing calls like:

const {app, appui} = require('our-cool-app');
    app.feature1.doSomething();
    appui.component.someButton.click();
    

Is there an easy solution to automatically generate d.ts files from the .js sources?

Answer №1

My own solution to a similar issue was to add a JSDoc @type comment above the problematic code. I encountered an error in a class where a getter returned a different class, resulting in this error popping up whenever the getter was used.

For example...

// File Foo.js
class Foo {
  get Bar() {
    return Bar;
  }
}
class Bar {};

// File Blah.js
const Foo = require('./Foo.js');
class Blah extends Foo.Bar {}     <--- The error occurred here

This was resolved by adding...

/**
 * @type Class
 */
get Bar() {
  return Bar;
}

Answer №2

To address this issue effectively, consider exporting the class with ES6 compatibility. When you export MyClass using module.exports, it is done in CommonJS format rather than ES6 format. In your mod1.js file, you can choose one of the following approaches:

export class MyClass {
    constructor(name) {
        this.name = name;
    }
}

module.exports = {
    MyClass,
};

Alternatively, I recommend a more visible method:

class MyClass {
    constructor(name) {
        this.name = name;
    }
}

module.exports = {
    MyClass,
};

exports { MyClass };

Implementing either of these options should yield positive results.

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

Adjust Tinymce size automatically when a key is held down for a prolonged period of

Having trouble with tinymce not automatically resizing when certain characters are pressed repeatedly. However, the height adjusts after releasing the key. Is there a method to auto resize tinymce during the key down event? I am utilizing angularjs ui-tin ...

Enhance the visual representation of live updates through the utilization of socket.io in Express

I'm using handlebars as the view engine for my express app. But I'm unsure how to append new data coming in from socket.io. router.get('/', function(req, res) { io.on('connection', function(client) { client.on( ...

What's the best way to create an onclick event for a li element that includes a pseudo-element ::before

I have successfully created a Timeline using HTML and CSS elements. The visual result is as follows: My goal is to enable users to click on the second circle, triggering a color change in the line that connects the first and second circles. This color tra ...

Utilizing .html() to convert JSON data into HTML content

I have thoroughly commented the code below in my attempt to retrieve JSON data and pass it to the 'results' div in my HTML view. However, this process seems to return nothing, making it challenging to debug since no output can be displayed on the ...

The unhandled type error rises with each scroll I make

Having been diligently working on my current website project, I encountered a puzzling issue. Upon writing code to implement smooth scrolling throughout the site, I found myself facing a persistent error that continues to escalate with each scroll up or do ...

What's causing this javascript to malfunction on the browser?

I encountered a problem with the code in my .js file. Here is a snippet of the code: $.extend(KhanUtil, { // This function takes a number and returns its sign customSign: function(num){ num = parseFloat(num) if (num>=0){return 1} ...

How can I access a file uploaded using dxFileUploader?

I am facing an issue with retrieving a file from dxFileUploader (DevExpress) and not being able to read it in the code behind. The file is only appearing as an object. Here is My FileUploader : { location: "before", ...

Looking to update this jQuery pop-up menu script to be compatible with Ajax functionality

I came across this script at The issue arises when the script is called multiple times, resulting in a cascade of pop-outs within pop-outs. I am currently exploring ways to prevent the execution of the script if the pop-out has already been set. Below is ...

Refresh the Document Object Model (DOM) and transmit the present time

I am having an issue with sending the actual current time when a button is clicked. Instead of getting the current time, I am receiving the time when the page initially loaded. This button is used to submit a form on Google Sheets using an API. This is th ...

QueryFailedError: Null values found in the "price" column - TypeORM - PostgreSQL

I have developed a straightforward table: import { Column, Entity, PrimaryGeneratedColumn } from "typeorm" @Entity() export class Test { @PrimaryGeneratedColumn() public id!: number @Column({ nullable: false }) public name!: string @ ...

Obtaining the complete JSON array in string format

I am currently using Fine Uploader to pass parameters in this way callbacks: { onSubmit: function(id, fileName) { this.setParams({ a: 'adm', b: '126', c: { fileID: id, ...

Error message: "PHP encounters an issue with jQuery due to absence of 'Access-Control-Allow-Origin' header"

I am currently attempting to make an external API call in PHP using AJAX and jQuery, but I keep encountering the error message saying "No 'Access-Control-Allow-Origin' header is present". The API does not support JSONP. Is there any workaround t ...

What is the best way to access data from a local JSON file in Gatsby when using TypeScript and GraphQL?

I'm updating my former gatsby site using TypeScript. I encountered an issue while trying to retrieve data from a local JSON file: There appears to be an error in your GraphQL query: Cannot find field "allNavigationLinksJson" on type "Q ...

Utilize JavaScript/jQuery to implement a prompt for saving downloaded files

Is it possible to use javascript or jquery to configure the setting mentioned above (Ask where to save each file before downloading)? ...

The variable <variable> is not meeting the 'never' constraint. Error code: ts(2344)

Currently, I am attempting to utilize Supabase alongside TypeScript. However, I encounter an error when trying to use functions like insert(), update(), upsert(), etc. Specifically, the issue arises when declaring the object I want to declare: "Type & ...

When utilizing a Javascript event listener within ReactJS with NextJS, the dynamically imported module without server-side rendering fails to load

Hello everyone, I am new to ReactJS and NextJS and would really appreciate some advice on the issue below. Thank you in advance! Here is my current tech stack: Node v16.6.1 React v17.0.2 Next.js v10.0.4 I'm working on implementing a carousel and si ...

What is the best method for accessing a value in IndexedDB while utilizing service workers?

I am feeling overwhelmed by the concepts of IndexedDB and serviceworkers as I try to transform them into a functional application. Despite my extensive research, including studying various examples, I am struggling to integrate the two technologies effecti ...

jQuery's AJAX functionality may not always register a successful response

Below is the code snippet I am currently working with: $(".likeBack").on("click", function(){ var user = $(this).attr("user"); var theLikeBack = $(this).closest(".name-area").find(".theLikeBack"); $.a ...

Which is the best choice for a large-scale production app: caret, tilde, or a fixed package.json

I am currently managing a sizeable react application in production and I find myself undecided on whether it is more beneficial to use fixed versions for my packages. Some suggest that using the caret (^) is a safer route, but I worry that this could poten ...

"Revolutionize Your Site with Endless Scrolling using q

I am currently in the process of developing a web application using create-react-app along with the packages Infinite-Scroller and qwest. (https://www.npmjs.com/package/react-infinite-scroller) (https://www.npmjs.com/package/qwest) This is how my code l ...