Is there a way to reach a class from within another class in TypeScript?

Let's take a look at my main class A

export class A {

    public sourceReference: string;

    public charge: Charge;
}

Here is how my Charge class is structured:

export class Charge {

    public chargeType: string;
    
    public chargeAccountNumber: string;

    public chargeCurrency: string;
}

Now, in the index file, I intend to utilize class A and populate the payload like so:

    import { A } from "./a";
    
    public static create(payload) {

      let myData = new A();

      myData.sourceReference = payload.sourceRef;
      myData.charge.chargeType = payload.type;
      myData.charge.chargeAccountNumber = payload.accountNumber;
      myData.charge.chargeCurrency = payload.currency

      return JSON.stringify(myData)

     }

The incoming payload data appears as follows:

payload = { sourceRef: "1234", type: '615-01', accountNumber: '123456', currency: 'USD'}

I can successfully access myData.sourceReference

However,

The issue arises when trying to access myData.charge, which returns as undefined. This results in undefined values for myData.charge.chargeType,

myData.charge.chargeAccountNumber
& myData.charge.chargeCurrency.

Error Message: TypeError: Cannot set property 'chargeType' of undefined

Answer №1

In the world of programming, we have a class known as A which contains a property called Charge.

However, it's important to note that this charge property doesn't currently hold any specific values - it's just a type.

For instance, in order for the class A to actually use the Charge class, an instance needs to be created, usually within the constructor method.

The constructor in this case should be implemented like so:

export class A {
  public sourceReference: string;
  public charge: Charge;

  constructor() {
     this.charge = new Charge()
  }

 ...

Answer №2

To pinpoint the issue, pay close attention to the exception message. In order to resolve it, you need to properly define myData.charge by using myData.charge = new Charge(). Afterwards, proceed to set its properties as follows:

myData.charge.chargeType = payload.type;
myData.charge.chargeAccountNumber = payload.accountNumber;
myData.charge.chargeCurrency = payload.currency

If you wish to elevate your coding style, consider crafting a constructor for the charge object in this manner:

export class Charge {
    
    constructor(chargeType:string, chargeAccountNumber:string, chargeCurrency:string){
    this.chargeType = chargeType;
    this.chargeAccountNumber = chargeAccountNumber;
    this.chargeCurrency=chargeCurrency;
    }

    public chargeType: string;

    public chargeAccountNumber: string;

    public chargeCurrency: string;
}

Once done, initiate the constructor like so:

myData.charge = new Charge(chargeType,chargeAccountNumber,chargeCurrency) 

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

How can one easily retrieve the callback function arguments from outside the function?

Here is a snippet of my code: var jenkins = require('jenkins')('http://192.168.1.5:8080'); var job_name = undefined; jenkins.job.list(function doneGetting(err, list) { if (err) throw err; job_name = list[0].name; }); jenkins. ...

Creating an array dynamically in response to an AJAX call

Is there a way to dynamically create an array after receiving an AJAX response? Upon getting the AJAX response, the variable data.villages contains the data. To iterate over its values, the jQuery each function can be used: $.each(data.villages, functio ...

Alter the URL and CSS upon clicking an element

Currently, I am faced with a challenge on my website where I have multiple pages that utilize PHP to include content and jQuery to toggle the display of said content by adjusting CSS properties. However, I am encountering difficulty in implementing this ...

toggle the class of the parent if the parent has a specific class

Can you provide some assistance with this? Javascript: $(document).ready(function(){ $(".tile a").click(function() { $(this).closest("div").toggleClass("selected_tile"); if($(this).parent().parent().hasClass("col-md-4")){ ...

Retrieve the webpage content (including any iframes) using a Firefox plugin

Hello there! I am currently working on retrieving data from a webpage that is updated using Javascript. Initially, I attempted to create a Java program to periodically fetch this page from the server, but the information was being updated too slowly. The ...

Using nested asynchronous loops to push items to an asynchronous queue without triggering the main callback

I have an async queue that I am populating with items from nested lists within a data object. Despite the queue processing everything, I am unable to reach my main callback function console.log('All done.'). I've stripped away unnecessary co ...

There seems to be an issue with the API call in Angular 4 as it is not working properly. The error message "No 'Access Control Allow Origin'

I am encountering an issue with the ticket system. Posting a ticket works fine, but commenting on a ticket does not work. Error: Failed to load http://localhost:3977/api/tickets/comment: No 'Access-Control-Allow-Origin' header is present on the r ...

Creating an event listener using a calendar icon

I am looking to create a custom datepicker <input type="text" name="Birth" id="calendarInput" required class="inputField" placeholder="31.12.2001"> <input type="date" name="Birth&qu ...

Struggling to get Deployd App to work, encountering issues with dpd.collection.first()

After successfully setting up the latest version of Deployd on my Windows 7 64 Bit system, I encountered an issue when trying to query a single object. For example, when using the code snippet below: var query ={"name":"Jack","empid":"10"}; dpd.employe ...

Typescript's array of functions

In my code, I currently have an engage(ability: number, opponent: Creature) function that is responsible for executing one of three different attacks based on the ability chosen. strike(opponent: Creature){} claw(opponent: Creature){} fireball(opponent: C ...

Introducing Vuetify 3's v-file-input with interactive clickable chips!

I noticed an unexpected issue with the v-file-input component in Vuetify3. In Vuetify 2, it was possible to use the selection slot to customize the display of selected files. This functionality still works in both versions, as mentioned in the documentatio ...

JavaScript code for client-side implementation using Node.js

As I work on developing a web application, I encounter the need to interact with an API that lacks JSONP/CORS support. Initially, my solution was to establish a server with PHP code and utilize ajax calls. However, my discovery of this node module offers ...

Creating a form that can identify both letters and numbers using JavaScript

Is it possible to create an <input> field that can recognize both letters and numbers while disregarding spaces and capitalization? Here is my current progress, aiming for the feedback to display as "right" when 9 H 6 U 8 f is entered in the field, ...

Is it possible to debug JavaScript within a Web Application using Webstorm?

For my AngularJS application that communicates with an ASP.NET Web API back-end, I have been using VS2013 for coding. After clicking the build button, I typically open the application in a browser and utilize Chrome Developer tools to debug the Javascript. ...

Guide on integrating cookiejar with HTTP2

I am currently facing a challenge in making http2 requests and incorporating a cookie jar or container in node.js. Despite researching online, I have not yet found a suitable solution. If, for instance, I wish to send the following http2 request: const cl ...

What are the steps to get the Dropdown Button to function in HTML and CSS?

Currently, I am in the process of constructing a website and have set it up so that when the window width is less than 768px, the navbar collapses into a vertical orientation. The issue I am facing is that even though the navbar collapses, the individual i ...

Using JavaScript, sift through various elements in a large array and extract only specific

I have retrieved an array containing 2400 objects from our server, totaling about 7MB in size, and I need to extract specific values from it. Currently, I am using a combination of the filter and slice methods: const keyword = 'whatever word'; ...

Can I send a JavaScript class to PHP as JSON in a different way?

As a beginner in this field, I am quickly learning and would greatly appreciate any kind of assistance. For example, I have an object like the following: function shape(name, size) { this.name = name; this.size = size; // additional function ...

Prevent the display of hyperlinks in the status bar when hovering over a hyperlink or button

The application I'm working on has a default status bar at the bottom of each screen that displays URLs linked to buttons and icons. For example: https://i.stack.imgur.com/ZFTsp.jpg I am trying to prevent the display of URLs associated with hyperlin ...

Error in typescript: The property 'exact' is not found in the type 'IntrinsicAttributes & RouteProps'

While trying to set up private routing in Typescript, I encountered the following error. Can anyone provide assistance? Type '{ exact: true; render: (routerProps: RouterProps) => Element; }' is not compatible with type 'IntrinsicAttribu ...