Access to property 'foo' is restricted to an instance of the 'Foo' class and can only be accessed within instances of 'Foo'

In my Typescript code, I encountered an error with the line child._moveDeltaX(delta). The error message reads:

ERROR: Property '_moveDeltaX' is protected and only accesible 
       through an instance of class 'Container'   
INFO:  (method) Drawable._moveDeltaX( delta:number):void

The code snippet causing this error is as follows:

class Drawable {

    private _x:number = 0;

    constructor() {}

    /**
     * Moves the instance a delta X number of pixels
     */
    protected _moveDeltaX( delta:number):void {
        this._x += delta;
    }
}

class Container extends Drawable {
    // List of children of the Container object 
    private childs:Array<Drawable> = [];

    constructor(){ super();}

    protected _moveDeltaX( delta:number ):void {
        super._moveDeltaX(delta);
        this.childs.forEach( child => {
            // ERROR: Property '_moveDeltaX' is protected and only accesible
            //        through an instance of class 'Container'
            // INFO:  (method) Drawable._moveDeltaX( delta:number):void
            child._moveDeltaX(delta);
        });
    }
}

I'm confused about why I am experiencing this issue. In other languages, accessing a protected method like this would work without any problems.

Answer №1

Your "childs" object is not visible to the inherited object. You have created a new instance that cannot access the protected method. Protected methods can only be accessed using super, not other instances.

This scenario would likely fail in c# as well.

Answer №2

Using the any type for casting is considered a makeshift solution. A better approach would be to abstract the interface from access levels:

  1. Develop an IDrawable interface that includes the methods of a Drawable object such as moveDeltaX.
  2. In this scenario, Container does not inherit from IDrawable; instead, the list will store IDrawable objects: private children: Array = [];
  3. The concrete children entities like Rectangle and Circle will implement the IDrawable interface as their base, ensuring that the fundamental methods can be accessed regardless of the specific type being referenced.
  4. If there is common functionality to be shared among different types, you could create a Drawable class that implements IDrawable (or consider a DrawableBase class and Drawable interface) and use it as a foundation for the distinct types.

Although less pertinent in javascript and TypeScript, in languages with robust Object-Oriented support, interfaces enable seamless implementation changes without requiring extensive modifications throughout the application.

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

Facing issues with the template URL not functioning properly during the migration from Angular 1.5 to Angular 6

I am currently in the process of migrating an Angular 1.5 project to Angular 6, but I've encountered an issue with the templateUrl not working in the Angular 1.5 component. The packages I am using are: Angular CLI 6.0.8 TypeScript 2.7.2 Angular 6.0.7 ...

typescript Parameter type dependency based on value is not functioning

interface AddDataRequest{ data:any } interface AddDataResponse{ id:string } interface ITest{ addData(json:AddDataRequest):Promise<AddDataResponse> removeData(json:AddDataResponse):Promise<boolean> } function testInterface<A e ...

Learn how to alter the website's overall appearance by changing the background or text color with a simple click on a color using Angular

Is there a way to dynamically change the background color or text color of the entire website when a user clicks on a color from one component to another? I know I need to use the Output decorator, but how can I implement this? style.component.html <di ...

Angular 5 ngx-modialog issue TS2307: Module 'ngx-modialog/plugins/vex' not located

After installing module ngx-modialog using the Angular 5 CLI like this: npm install --save ngx-modialog I then added it to my app.module.ts: import { VexModalModule } from "ngx-modialog/plugins/vex"; import { ModalModule } from "ngx-modialog"; @NgModul ...

Issue with locating assets in Angular 6 build

Hey there! I'm currently facing an issue while trying to build my angular project. In the project, I am using scss with assets, and below is a snippet of how I have defined the background image: .ciao { background-image: url("../../assets/images/bc ...

Commitments, the Angular2 framework, and boundary

My Angular2 component is trying to obtain an ID from another service that returns a promise. To ensure that I receive the data before proceeding, I must await the Promise. Here's a snippet of what the component code looks like: export class AddTodoCo ...

Categorize messages based on the date they were last read in Angular

I am looking to organize my chat application messages by date, similar to the layout in Microsoft Teams app. Here is an example of the message data: [ { "id": 577, "source": { "userID": 56469, ...

Incorporating type declarations for a basic function that returns a wrapper function for other functions

In my vanilla JS code, I have a sophisticated function that is exported and I am attempting to create a .d.ts file for it. Unfortunately, my previous attempts at writing the .d.ts file have not been successful in passing the types from one stage of the fu ...

How can I access a TypeScript variable from a global var set in a .cshtml file?

I have defined several variables in my .cshtml file to be used in my angular services: <script> var _APIURL = '@(Url.Content("~/Admin/api/"))'; var _AREAURL = '@(Url.Content("~/Admin/"))'; var _APPURL = &a ...

After the installation of Storybook, there is a duplicate identifier error that arises with 'LibraryManagedAttributes'

Upon running the command npx storybook@latest init for setting up Storybook, which results in modifying package.json, I encounter an issue where I cannot run the project using npm due to: Error: node_modules/@types/react-dom/node_modules/@types/re ...

Warning in VSCODE: Use caution when using experimental decorators

I have been working on an Angular2-Typescript application and created the project using angular-cli with the command: ng new myApp However, I am facing a warning issue when creating a new component with the @Component tag. I have tried to resolve this p ...

Participating in consolidated data

I need to merge data from my trainings-table with my users-table. The structure of the data is as follows: - users - key1 - name - trainingIds - t_key1 - t_key3 - trainings - t_key1 - name - description - t_k ...

What could be causing this error in a new Next.js application?

After multiple attempts, my frustration and disappointment in myself are causing a headache. Can someone please assist me? I am trying to create an app using the following command: npx create-next-app@latest --ts Immediately after running next dev, I enco ...

What could be causing the issue with converting a Firestore timestamp to a Date object in my Angular app?

Currently, I am developing an Angular project that involves using a FireStore database. However, I have encountered a problem with the setup. Within my Firestore database, I have documents structured like the example shown in this image: The fields start ...

Leveraging the power of literal types to choose a different type of argument

My API is quite generic and I'm looking for a typed TypeScript client solution. Currently, my code looks like this: export type EntityTypes = | 'account' | 'organization' | 'group' export function getListByVa ...

In order to set a condition for the mat date picker to display a text box in Angular if the selected date is for someone under 18 years old

I need assistance with displaying a text field based on age validation. The requirement is to show the input field only if the age is less than 18. Below is the code snippet I am currently working with: <form [formGroup]="form"> ...

Angular ensures that the fixed display element matches the size of its neighboring sibling

I have a unique challenge where I want to fix a div to the bottom of the screen, but its width should always match the content it scrolls past. Visualize the scenario in this image: https://i.sstatic.net/i7eZT.png The issue arises when setting the div&apo ...

Ways to transmit information or notifications from a service to a component

Currently, I am utilizing Angular 6 and have the upload file control on three different screens (three various components). Each of these screens calls the same method UploadFile(). The main issue arises when I need to make any changes to this method, as ...

Displaying nested web service array data in Angular 4

I created a project that retrieves data from a web service API. However, the API contains nested arrays that also need to be displayed. How can I access the data from these nested JSON arrays? What is the correct way to extract this data within the HTML co ...

Utilize TypeScript to import a JSON file

I am trying to incorporate a JSON file using TypeScript, which contains data about different regions in Italy along with their respective capitals. Here is a snippet of the data: { "italia": [ { "regione": "Abruzzo", "capoluoghi": [ ...