Can a parent class retrieve an attribute from one of its child classes?

Within my code, I have a parent class where I am creating a function called store-relation and a child class that defines a table in the store. The issue arises when I try to connect the save() function from the parent class to the child's table which is not defined until later. I attempted to solve this by passing the child's tableName attribute to the parent's constructor, but my linter flagged an error stating that super must be called before referencing this.

Here is the snippet of the parent class:

export class StoredObject {
    constructor(private tableName: string) {}

    public save() {
        store.collection(this.tableName) //...
    }
}

And here is the child class:

export class Inventory extends StoredObject {
    tableName = "inventory";

    constructor(
        public myVar //...
    ) {
        super(this.tableName)
    }
}

I understand that one solution is to use a getter function to return the value of this.tableName, but that feels like a workaround. Another option would be to hardcode the string directly into super (e.g., in the Inventory constructor, using { super("inventory") }), but that approach seems less elegant. It seems like there should be a more conventional way to achieve what I'm attempting to do, but so far I haven't been able to find it.

Answer №1

Check out Ryan Cavanaugh's reply here

To elaborate,

The sequence of initialization is as follows:

  1. Initialization of properties in the base class
  2. Execution of the base class constructor
  3. Initialization of properties in the derived class
  4. Execution of the derived class constructor

You have assigned the responsibility of initializing the tableName property to your superclass, which needs to be done before creating an instance of the subclass. Either pass in "inventory" or modify this relationship accordingly.

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

The Date_Format field in the JSON-Data is not displaying

Greetings and apologies for my limited English skills :-) I am facing a challenge with my JSON data. In my MySQL database, I have stored dates in the format YYYY.MM.DD. However, I require the format DD.MM.YYYY. So, I modified the query as follows: $rs = ...

Is Ajax capable of producing multiple outputs at once?

I am looking to retrieve data from a product.json file that contains two objects: (1) object for CCTV camera products (2) object for Laptop products. When a specific button is clicked, I want to access the data for LAPTOP products and the same for CCTV. ...

Pause the timer once it has reached a specific duration

My challenge involves utilizing a javascript timer that starts at 00:00 and needs to stop at 00:10 (10 seconds duration). The issue at hand is how to continuously monitor the current timer value to appropriately pause it after the designated 10 seconds ha ...

Using TypeScript generics to efficiently differentiate nested objects within a parsed string

Consider the following type code: const shapes = { circle: { radius: 10 }, square: { area: 50 } } type ShapeType = typeof shapes type ShapeName = keyof ShapeType type ParsedShape<NAME extends ShapeName, PROPS extends Sh ...

Exploring the capabilities of chromaprint.js within a web browser

I'm currently in the process of developing a music streaming platform and I'm looking to include the chromaprint.js library for deduplication purposes. In my workflow, I utilize browserify and gulp. Despite the fact that the library claims it ca ...

Encountering problem with Karma, Angular 7, and FontAwesome: Unable to attach 'icon' property to 'fa-icon' as it is not recognized

An issue arises when attempting to bind to 'icon' since it is not recognized as a property of 'fa-icon'. During the execution of this test within people.component.spec.ts import { async, ComponentFixture, TestBed } from "@angular/core ...

Is it possible to broaden Tagged/Discriminated Union in TypeScript within a separate module?

In my system, I have established a method for transferring JSON messages through a socket connection. The communication involves Tagged Unions to categorize different message types: export type ErrorMessage = { kind: 'error', errorMessage: Error ...

Navigating the intricacies of retrieving network errors within an AngularJS application requires a deep

I've encountered the following code snippet in abcd.js: $http({url: 'some url' , method: 'POST', data: , headers: {} }).then(function(response)) { ............. }, function error(response) { .............. }) When an error occurs ...

Problems encountered with an API for newsletter signups

The form I created allows users to input their email and sends it to my Sendgrid contacts list. However, there are a couple of issues that need addressing: After submission, the page gets stuck on loading The frontend logic is not functioning as desi ...

Quick fix for obtaining only one response

I'm facing a dilemma where I need to redirect the user to the dashboard page after they log in, but also send their JSON details to my client-side JavaScript. While I know that there can only be one res.send/end/json in a response and dynamic data can ...

Placing a hyperlink within template strings

Currently, I am working on implementing a stylish email template for when a user registers with their email. To achieve this, I am utilizing Express and Node Mailer. Initially, my code appeared as follows: "Hello, " + user.username + ",&bs ...

Is there a way to have my accordion adjust automatically?

I have developed a dynamic accordion component that populates its values from the parent component. However, I am facing an issue where each accordion does not respond individually to clicks. Whenever I click on any accordion, only the first one expands an ...

Change an array of objects with parent child connections into a nested object structure

Imagine having a collection of objects with parent-child relationships like the one shown below: [ { A1: [ "B1" ] }, { B1: [ "C11", "C12", "C13" ] }, { C11: [ "D100", "D111", "D112" ...

Guide on adding JSON data from a web service whenever a function is invoked in AngularJS

I am currently calling the getData function every second and everything is working fine except for the appending functionality. Whenever the function is called, AngularJS replaces the old data with new data, but I actually want to append the new data aft ...

Unable to execute multiple instances of Selenium PhantomJS concurrently

I have encountered an issue while using Selenium's node.js API to run PhantomJS instances against a series of web pages. The code that I have written to perform actions on the pages is functioning correctly, but it appears that only one instance of Se ...

Ways to limit the type based on the value of the argument

Is it possible to narrow down the type of the library in the demo code provided? Can we use the factory function to create a new function fnP with an exact type instead of any? const libOne = { p: () => 0, q: () => 1, }; const libTwo = { x: ( ...

Node.js: Module not found error

When I run the command below to install a module from the NPM registry: npm install dc All files are successfully installed, but upon running the script dc, it fails to resolve a dependency. $ node web-test.js module.js:340 throw err; ^ Error: ...

Retrieving the dimensions of an iframe using JavaScript

I currently have an iframe on my page with a height of 0px and width of 100px that I would like to access using JavaScript. Although I can grab the iframe element using window.frames[0], I'm struggling to retrieve the actual width and height values. ...

Using jQuery JSONP only functions with URLs from the same site

I am looking to send a request to an API that returns data in json format. The API is located on a sub-domain of the domain where my script will be running (although currently it's on a completely different domain for development, localhost). My unde ...

React Native application crashes on Android 12 and above when run on an emulator

Currently in the process of creating a music application named Wavelet. Listed below are my dependencies: package.json Typically, I debug on an Android 11 emulator; however, when switching to an Android 12 emulator or using my physical device running on A ...