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

The image is malfunctioning in the production environment, but functions perfectly on the localhost server

Currently, I am in the process of creating a website utilizing Next.js and Mantine. In order to incorporate my logo into the Header section, I utilized the Image component from next/image. Unfortunately, upon deployment, the image does not display as inten ...

Creative Solution for Implementing a Type Parameter in a Generic

Within my codebase, there exists a crucial interface named DatabaseEngine. This interface utilizes a single type parameter known as ResultType. This particular type parameter serves as the interface for the query result dictated by the specific database dr ...

deleting the existing marker before placing a new marker on the Mapbox

Upon the map loading with GeoJson data, I have implemented code to display markers at specified locations. It works flawlessly, but I am seeking a way to remove previous markers when new ones are added. What adjustments should be made for this desired func ...

Leveraging Angular's catchError method to handle errors and return

One of my challenges involves a model class that represents the server response: class ServerResponse { code: number; response: string; } Whenever I make api calls, I want the response to always be of type Observable<ServerResponse>, even in ...

"Error 404: The file you are looking for cannot be found on [custom company domain]. Please check

My attempts to retrieve a Google Drive file using its file ID with a service account in NodeJS have been unsuccessful. The requests are failing with an error indicating a lack of access: code: 404, errors: [ { message: 'File not found: X ...

Combining Interfaces in Typescript: Utilizing Union Types with a Base and Extended Interface

I'm facing an issue with the following code snippet interface BaseA { a: number; } interface SpecialA extends BaseA { b: number; } type A = BaseA | SpecialA const a = { a: 5, b: 5 } as A console.log(a.b) Even though I thought the code was ...

Having trouble with Typescript module path resolution for .js files?

I have embarked on a project in React and I am eager to begin transitioning the js files to typescript. The setup for aliases seems to function smoothly when importing .tsx within another .tsx file, however, it encounters issues when attempting to import . ...

Leveraging Ionic 2 with Moment JS for Enhanced TimeZones

I am currently working on integrating moment.js with typescript. I have executed the following commands: npm install moment-timezone --save npm install @types/moment @types/moment-timezone --save However, when I use the formattime function, it appears th ...

Intellisense fails to function properly after attempting to import a custom npm package

I've encountered an issue with a custom npm package that I created using storybook. The components function properly in other projects when imported, but the intellisense feature is not working as expected. Interestingly, when I import the same compon ...

PlatypusTS: Embracing Inner Modules

Incorporating angular, I have the capability to fetch object instances or import modules using the $injector in this manner: export class BaseService { protected $http: angular.IHttpService; protected _injector: angular.auto.IInjec ...

When running `aws-cdk yarn synth -o /tmp/artifacts`, an error is thrown stating "ENOENT: no such file or directory, open '/tmp/artifacts/manifest.json'"

Starting a new aws-cdk project with the structure outlined below src └── cdk ├── config ├── index.ts ├── pipeline.ts └── stacks node_modules cdk.json package.json The package.json file looks like this: " ...

Blurry text issue observed on certain mobile devices with Next.js components

There continues to be an issue on my NextJS page where some text appears blurry on certain mobile devices, particularly iPhones. This problem is only present on two specific components - both of which are interactive cards that can be flipped to reveal the ...

What is the best way to ensure that a mapped type preserves its data types when accessing a variable?

I am currently working on preserving the types of an object that has string keys and values that can fall into two possible types. Consider this simple example: type Option1 = number type Option2 = string interface Options { readonly [key: string]: Op ...

Having trouble with Angular 2 not properly sending POST requests?

Having some trouble with a POST request using Angular 2 HTTP? Check out the code snippet below: import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import 'rxjs/add ...

Tips for refreshing the appearance of a window in angular when it is resized

I have a chat feature integrated into my application. I am looking to dynamically resize an image within the chat window when the width of the window falls below a certain threshold. Is there a method available to modify the CSS style or class based on the ...

How to invoke a method in a nested Angular 2 component

Previous solutions to my issue are outdated. I have a header component import { Component, OnInit } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; import { Observable } from 'rxjs/Observable'; ...

What could be causing Typescript Intellisense to not display Object extensions?

Let's take a look at this unique way to extend the Object type: interface Object { doSomething() : void; } Object.prototype.doSomething = function () { //perform some action here } With this modification, both of the following lines will c ...

Sending real-time data from the tRPC stream API in OpenAI to the React client

I have been exploring ways to integrate the openai-node package into my Next.js application. Due to the lengthy generation times of OpenAI completions, I am interested in utilizing streaming, which is typically not supported within the package (refer to he ...

Error Encountered in Cypress: "Tried to wrap warn but it is already wrapped"

Objective: Utilize Cypress and Typescript to test for warnings and errors on the console. Error Encounter: An attempt was made to wrap warn, which is already wrapped. Snippet: describe.only("Unauthenticated User", () => { it("No C ...

What is the best way to create a case-insensitive sorting key in ag-grid?

While working with grids, I've noticed that the sorting is case-sensitive. Is there a way to change this behavior? Here's a snippet of my code: columnDefs = [ { headerName: 'Id', field: 'id', sort: 'asc', sortabl ...