Unveiling the approach to retrieve a private instance variable within a protected method using TypeScript

I have a scenario where an abstract class contains an abstract method that is then implemented by a child class. The implemented method in the child class needs to update a private instance variable specific to the child class. Subsequently, I aim to retrieve the value of this private variable using a getter method.

To demonstrate the issue, I have prepared some sample code on the playground.

Animal serves as the base class with the abstract method someAbstractMethod():

abstract class Animal {

    protected abstract someAbstractMethod(): void;

    constructor() {
        document.writeln("A new animal is born<br>");
        this.someAbstractMethod();                          //  <-- call into child class
    }  
}

Snake inherits from Animal and implements the abstract method someAbstractMethod(). This class includes a getter/setter for accessing the value of the private instance variable someLocalVariable:

class Snake extends Animal {

    private someLocalVariable: string = "initial value";

    constructor() {
        super();
    }

    get someValue() {
        document.writeln("Called getter for someValue<br>");
        return this.someLocalVariable;
   }

    set someValue(value: string) {
        document.writeln("Called setter for someValue<br>");
        this.someLocalVariable = value;
    }

    protected someAbstractMethod() {
        document.writeln("Called someAbstractMethod()<br>");
        this.someLocalVariable = "now set to something new";        //   <-- instance variable not updated (or in another scope)
    }
}

Firstly, instantiate a new Snake object, followed by retrieving the value of the private instance variable via a call to sam.someValue:

let sam = new Snake();
document.writeln("Value of someValue: " + sam.someValue);   

Unexpected Outcome

Console Output:

    A new animal is born
    Called someAbstractMethod()
    Called getter for someValue
    Value of someValue: initial value

The value returned by sam.someValue is 'initial value', despite the fact that the someAbstractMethod() was called earlier and should have updated the value to 'now set to something new'

Answer №1

Upon discovering this related question, I stumbled upon the solution to my query.

Solution Found

The key adjustment was made in the class Snake. The assignment to the variable someLocalVariable was removed.

class Snake extends Animal {

    private someLocalVariable: string; // = "initial value";         <--- remove assignment

    constructor() {
        super();
    }

    get someValue() {
        document.writeln("Called getter for someValue<br>");
        return this.someLocalVariable;
    }

    set someValue(value: string) {
        document.writeln("Called setter for someValue<br>");
        this.someLocalVariable = value;
    }

    protected someAbstractMethod() {
        document.writeln("Called someAbstractMethod()<br>");
        this.someLocalVariable = "now set to something new";
    }
}

View updated code in playground

The issue stemmed from the fact that the initialization of someLocalVariable occurred after the constructor call. While someAbstractMethod() sets the value correctly, upon returning from the constructor, the private instance variable is initialized with "initial value". Removing the assignment ensures that the value of someLocalVariable remains unchanged post constructor execution.

However, there are still concerns with this solution as enabling compiler options --strictPropertyInitialization and --strictNullChecks leads to compilation failures. Although acceptable currently, it does raise doubts about potential errors in the approach taken.

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

Discover the complete guide on incorporating a JavaScript library with additional dependencies in Angular 2

I am a beginner with angular 2 and I am attempting to integrate the Miso Dataset JavaScript library into my angular 2 project. The Miso library requires other JavaScript libraries as dependencies. Although I have included all the necessary JavaScript file ...

Minimize the number of axios requests made every time a Vue component is displayed

I am relatively new to Vue, so please bear with me as I may not have all the knowledge in this area. Within one of my child components (Product_Collection.vue), I am making an axios request to retrieve products from my Shopify store using their GraphQL ...

Sending JSON data to an API endpoint

I am having trouble with making a JSON Post request to the Simpleconsign API, as I keep getting a 0 error from the browser. Below is my code snippet: <script type="text/javascript"> JSONTest = function() { var resultDiv = $("#resultDivContainer ...

Selecting either "THREE.NearestFilter" or "THREE.LinearFilter" will result in the black plane

During my experimentation with the THREE.js library, I encountered a notification stating: THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. To address this issue, I made the ...

Exploring the dynamic possibilities of creating a loop within a bootstrap grid layout

I am currently working on extracting data from an external API and I am looking to map this data to a SimpleCards component. My goal is to loop through the data and render it using a bootstrap grid system. Specifically, I want each row to have 4 columns (o ...

React Typescript: The element is implicitly assigned an 'any' type as the type does not have an index signature

While attempting to locate a key of an object using an item from an array, I encountered an error... An Element implicitly has an 'any' type because type lacks an index signature I've replicated the issue in this sandbox https://codesandbo ...

An issue occurred when attempting to retrieve JSON data using an Ajax

After making an ajax call below, I encountered an error that left me puzzled. The variable 'response' in the success function is structured as follows: {"status": "complete", "username": "test", "error": "0", "message": ""} Surprisingly, when I ...

Connection point for linking offspring records to their guardian without returning any results

I am currently using mongoose and express to generate a collection of blog categories with their respective blog posts based on the category_id. My approach involves retrieving all categories, looping through them using underscore, and for each category, ...

Instructions for setting the value of a <input> element using scope

Having Trouble Passing Scope Value to Hidden Input Type I am facing an issue with passing the scope value to a hidden input type. Despite my efforts, I am unable to make it work as intended. Instead of displaying "PremiumVal", I need it to display "75" ba ...

continuously replacing keywords with hyperlinks occurs an endless number of times

Struggling to insert hyperlinks around specific keywords without endless replacements occurring: var replacements = [ { txt: 'magicFunction', link: 'https://www.example.com/doc/api/magicFunction.htm' }, ]; $(function() { $.each( ...

Removal of splash screen upon initial visit to the index screen

As the title suggests, I am facing an issue with my Splash screen on index.php. I want it to disappear after loading and not show up each time index is loaded. Any hints or suggestions on how to achieve this would be greatly appreciated. Thank you in adva ...

Having trouble getting Vue.js data to show up on the screen. I'm attempting to show a list of todos, but all that

I'm currently working on my App.vue file where I have set up the data for a todo list. However, despite creating an array of todos and attempting to display them, nothing is showing up on the screen. I'm at a standstill and could really use some ...

How to Access Users' Feeds from External Websites using Instagram API

I'm currently attempting to retrieve the most recent photos posted by a specific user. While browsing this website, I've come across numerous solutions claiming it's feasible to accomplish this task without needing an authentication token ( ...

Ways to import a library in JavaScript/TypeScript on a web browser?

I'm currently working on a project that involves a TypeScript file and an HTML page. Right now, I am loading the necessary libraries for the TypeScript file in the HTML Page using script tags like <script src="https://unpkg.com/<a href="/cd ...

Retrieve information from subcategories in the Realtime Database using Firebase

Trying to access message inputs from ALL users has been a challenge. While it can be done for a specific user, the goal is to do so for all users by specifying in the code. Each UID is unique, adding complexity to the process. The Realtime Database struct ...

What is preventing me from being able to reach the instance of Cropper JS?

I'm facing some issues with executing the loadImage() function as I am unable to access the variable cropper. My ultimate objective is to run cropper.getCroppedCanvas and save its output value into an input field so that I can transmit it via AJAX. T ...

Customizing AngularJS directives by setting CSS classes, including a default option if none are specified

I have designed a custom directive that generates an "upload button". This button is styled with bootstrap button CSS as shown below: <div class="btn btn-primary btn-upload" ng-click="openModal()"> <i class="fa fa-upload"></i> Upload & ...

obtain information beyond the prescribed boundaries

Having a slight issue, I am trying to return an array using a function in Angular. I am processing my data within an anonymous function and when I try to return the array, it ends up empty. I'm not sure what to do... getCurrentExchangeTo : function( ...

Ensure that the header smoothly navigates to a specific section within a separate component

Should I have this app that in the end has just 1 page? My current file structure is divided per section. I want to create a header that when clicked scrolls to a certain section (which is located in another component, not in the same file as these compone ...

The comparable Angular 2 Typescript code to access the token stored in cookies would be

Currently, I am in the process of converting my Angular 1 Javascript code to Angular 2 Typescript. I am facing a challenge in figuring out how to convert the following line into Angular 2 Typescript: $cookies.token ...