Can you explain the concept of cross referencing classes in Javascript/Typescript?

I am encountering difficulties with cross-referencing classes that are defined in the same file.

// classes.ts
export class A extends BaseModel implements IA {
  static readonly modelName = 'A';
  b?: B;
  symbol?: string;

  constructor(object: IA | A = {} as IA) {
    super(object);
    const { symbol, b } = object as A;
    this.symbol = symbol;
    this.b = b;
  }
}


export class B extends BaseModel implements IB {
  static readonly modelName = 'B';
  a?: A[];
  constructor(object: IB | B = {} as IB) {
    super(object);
    const { a } = object as B;
    this.a = a as A[];
  }
}

The error I receive looks like this:

Uncaught ReferenceError: Cannot access 'B' before initialization
    at Module.../../../../libs/platform/src/data/models/common/uom.ts (uom.ts:13)
    at __webpack_require__ (bootstrap:84)
    at Module.../../../../libs/platform/src/data/models/common/common-models.ts (main.js:27248)
    at __webpack_require__ (bootstrap:84)
    at Module.../../../../libs/platform/src/data/models/common/index.ts (index.ts:1)
    at __webpack_require__ (bootstrap:84)
    at Module.../../../../libs/platform/src/data/models/index.ts (index.ts:1)
    at __webpack_require__ (bootstrap:84)
    at Module.../../../../libs/platform/src/data/index.ts (index.ts:1)
    at __webpack_require__ (bootstrap:84)
    at Module.../../../../libs/platform/src/index.ts (index.ts:1)
    at __webpack_require__ (bootstrap:84)
    at Module.../../../../libs/platform-frontend/src/core/client/frontend-client.ts (index.ts:1)
    at __webpack_require__ (bootstrap:84)
    at Module.../../../../libs/platform-frontend/src/core/client/index.ts (index.ts:1)
    at __webpack_require__ (bootstrap:84)

Here are my babel and tsconfig files:

// babel.config.json
{
  "presets": [
    "@nrwl/web/babel",
    "@nrwl/react/babel"
  ],
  "plugins": [
    "babel-plugin-transform-typescript-metadata"
  ],
  "babelrcRoots": [
    "*"
  ]
}


//tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "downlevelIteration": true,
    "types": ["jest", "node", "cypress","reflect-metadata"],
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "rootDir": ".",
    "sourceMap": false,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "importHelpers": false,
    "target": "es5",
    "allowJs": true,
    "typeRoots": ["node_modules/@types"],
    "lib": [
      "es2017",
      "es6",
      "dom",
      "es2016",
      "esnext.asynciterable",
      "es5",
      "scripthost",
      "es2015.promise",
      "es2015.collection"
    ],
    "baseUrl": ".",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true,
    ...
    ...
}

I am confused as to why it works fine depending on the babel config. I am attempting to integrate inversify into my codebase, for which I need to include babel-plugin-transform-typescript-metadata in the babel configuration. After adding the plugin, I start getting errors on each class with cross-referencing that were previously working correctly without the plugin. So,

  • What is causing these issues?
  • How does it work fine based on the babel config?
  • What can I do to fix it since the classes are not even in separate files to cause circular dependencies?

Answer №1

It seems that the problem stemmed from the use of "babel-plugin-transform-typescript-metadata". By replacing this plugin with "babel-plugin-parameter-decorator", the circular dependency issue was solved without further intervention.

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

Navigating the changes of daylight savings time requires proper management

I am seeking a solution to manage daylight saving time using momentjs. When receiving a datetime value (such as 2022-04-05T10:59:13.640683) from the backend in a front-end application, I need to determine if I am in DST in order to display the correct date ...

Ways to send information from a child component to its parent component when a button is clicked in the

Being new to Angular, I am faced with a challenge of organizing a large form into smaller modular components. I have created multiple child components and integrated their selectors in the main parent component. In the parent component, there is a 'sa ...

Using ChartsJs to visualize input data formatted in the German data format

I am relatively new to working with Charts.js, but I will need it to generate some visually appealing graphs for my website. In the background, I have a Django project running that calculates a specific set of numbers for me. Due to the language setting in ...

Utilize the requestAnimationFrame function to dynamically determine the size and color

My initial goal was to develop a program that generates a circle, gradually shrinking until it vanishes. This circle was supposed to continuously repeat this animation while transitioning between colors (starting from one color and ending in another). Al ...

Exclude items from AngularJS watch list

Is there a way to manually run a digest loop on specifically selected watches? Take, for example, the scenario where I need a directive that constantly displays the current time (including seconds), but without triggering the digest loop every second. One ...

Guide on integrating Amazon S3 within a NodeJS application

Currently, I am attempting to utilize Amazon S3 for uploading and downloading images and videos within my locally running NodeJS application. However, the abundance of code snippets and various credential management methods available online has left me fee ...

finding the initial element within an object using lodash in javascript

Recently, I came across some data in the form of an array of objects. For instance, let me share a sample dataset with you: "data": [ { "name": "name", "mockupImages": "http://test.com/image1.png,http://test.com/image2.png" }] ========================== ...

Guide on implementing a redirect to a different page following form submission with the inclusion of a loading screen

<form action='page.html' method='post'> <input type="text" name="name" placeholder="Enter your name here"> <input type="submit" value="submit"> </form> The cod ...

Configuring Angular to use ES6 syntax

Trying to integrate angular google maps with es6 syntax has been a challenge for me. In es5, the code typically looks like this: .config(function(uiGmapGoogleMapApiProvider) { uiGmapGoogleMapApiProvider.configure({ // key: 'your api key&ap ...

Transferring documents using JavaScript

I have been using the following method to upload files to my Laravel backend: setFile(id, e) { let self = this; let reader = new FileReader(); reader.readAsDataURL(e.target.files[0]); reader. ...

What is the best way to transfer properties to a different component using the onClick event triggered by an element generated within the map function?

I am currently working on an application using react to retrieve data from a mongodb database. Within one of the components, called Gallery, I have integrated a map function to display a list of items. My goal is to implement an onClick event for each elem ...

Error: The window object is not found in this context when initializing the Commerce module from the commerce.export.js file located in the node_modules folder within the @chec

I have been working with the pages router and custom app file (_app.js) https://nextjs.org/docs/pages/building-your-application/routing/custom-app It seems that the issue may be within my _app.js file, where I have the following code: import '../glo ...

Glitch found in Safari involving innerText of elements

Hey everyone, I posted this question not too long ago but now I have some images to share regarding the issue with Safari. When checking the console in Safari, the following text is displayed: <div id="rot3posDisp" class="rotDisp">C</div> Ho ...

Is resizing possible using the Canvas identifier?

Is it possible to adjust the canvas size to match the width of the page using the canvas id's style in the html? Then in your javascript code for the canvas, can you have resize listeners that are responsive to the canvas size at any given time? I c ...

Internet Explorer is failing to show the results of an ajax call retrieved from the

Need help with this code block: $(document).ready(function() { dataToLoad = 'showresults=true'; $.ajax({ type: 'post', url: 'submit.php', da ...

Could there be an issue with my function parameters, or is there another underlying problem?

Hey there! I've been working on this function, but it doesn't seem to be running quite right. Here's the code: function chooseCols(colTag, tagName) { // Set column name var column = $('.tagChooser:eq(&apo ...

How can I use jQuery to separate special characters from letters in a string?

I'm facing an issue with my code related to validation. There is a existing validation in place that restricts users from entering letters and special characters in a textfield. Now, I need to incorporate this validation into my code but I'm uns ...

What is the best way to retrieve information from a database using JSON with PHP, JQUERY, and

Trying to retrieve data from a MySQL database and pass it to a JavaScript file has been quite a challenge. Despite searching extensively online, the examples I found didn't work in my specific scenario. .html file <!DOCTYPE html PUBLIC '-//W ...

Harnessing the power of data within different components

In my setup, I have two vital components in play. The initial one is responsible for presenting a list of items, while the second dictates the design and layout of these items. These items reside in an array located within the app.vue file. Here lies my p ...

How can we prevent Material-UI and Redux-form from re-rendering when an option is clicked in the select input?

I am facing an issue with rendering options dynamically. Whenever I click on the select or the options, the component re-renders and changes the options. As a result, I need to click twice to select an option in the dropdown. This re-rendering is happening ...