Create attributes that share the identical name as certain properties of the parent class

Upon extending a module, I have encountered an issue related to declaring private properties. Specifically, when I attempt to declare a method like init() as private, an error message is generated:

Types have separate declarations of a private property 'init'

It seems that the problem arises from having the same method in the superclass. However, I find it inconvenient to have to use different names just because the method is already taken in a class that is inaccessible to me due to its private nature!

My intention in declaring the method as private was to prevent such conflicts. I don't want to override it, but I also don't see why this should restrict me from declaring it in other classes. What purpose does this restriction serve anyway?

Answer №1

In my opinion, the reason behind this behavior lies in the prototype-based nature of javascript.
Let's take a look at the following code snippet:

class A {
    public constructor() {
        this.method();
    }

    private method() {
        console.log("A");
    }
}

class B extends A {
    private method() {
        console.log("B");
    }
}

new B();

One would expect the console to display "A" since we are calling a private method within the constructor of class A, which should not be overridable by a subclass. However, the compiled code actually results in:

var A = (function () {
    function A() {
        this.method();
    }
    A.prototype.method = function () {
        console.log("A");
    };
    return A;
}());
var B = (function (_super) {
    __extends(B, _super);
    function B() {
        _super.apply(this, arguments);
    }
    B.prototype.method = function () {
        console.log("B");
    };
    return B;
}(A));

Upon execution, the console will show "B" instead of "A" due to the method in the prototype of B overriding the original function. This behavior resembles that of a protected method rather than a private one.

In light of this, there are three possible solutions:

  • Use distinct names for private methods in each class
  • Switch from private to protected methods, maintaining the same functionality while indicating the nature of the method in the code
  • Introduce a base class for common public/protected methods and define private methods in the subclasses

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

Using Angular to make an HTTP POST request to fetch data

My trusty .net backpack has been working flawlessly. However, I encountered an issue when trying to connect it with the Angular front end. All backend requests are post requests and require passing an ApiKey in the body of each request. Interestingly, ever ...

Unable to inject NgControl into validator directive in Angular 6

I've encountered a challenge while trying to create a custom validator for a template-driven form. I'm aiming to constructor inject the NgControl of the host element, which is equipped with an NgModel directive. Unfortunately, I'm consistent ...

Retrieve input value in Angular 8 using only the element's ID

Can the value of an input be obtained in Angular 8 with TypeScript if only the element's id is known? ...

React: Unable to locate an index signature with a parameter of type 'string' on type N

While working with a React component, I encountered an issue when trying to access a property from my component state using a key. My editor showed the following warning: Element implicitly has an 'any' type because expression of type 'str ...

Attempting to redeclare a previously exported variable will result in an error stating: "Cannot

I'm currently facing an issue with a npm module located in a different directory that I've linked to another project using npm link. Despite successfully compiling the typescript, when I try to import the module and use its function, I encounter ...

Is there a way to alter the date format for input elements within formGroups using Angular 7?

When the input is of type 'Date', the date format is dd/MM/yyyy. I need to convert the date format from MM/dd/yyyy to dd/MM/yyyy (Turkish Format and Turkish Calendar). Below is the code snippet. <form [formGroup]="opportunityForm" (ngSubmit ...

Searching for a specific document using AngularFirestore - what's the best method?

Is it possible to create an Observable that is limited to a single document? While the code provided creates an Observable for querying multiple documents: foo.component.ts import { AngularFirestore } from '@angular/fire/firestore'; import { O ...

Angular Build Showing Error with Visual Studio Code 'experimentalDecorators' Configuration

Currently experiencing an issue in VSC where all my typescript classes are triggering intellisense and showing a warning that says: "[ts] Experimental support for is a feature that is subject to change in a future build. Set the 'experimentalDeco ...

The TS2583 error in TypeScript occurs when it cannot locate the name 'Set' within the code

Just started my Typescript journey today and encountered 11 errors when running tsc app.ts. Decided to tackle them one by one, starting with the first. I tried updating tsconfig.json but it seems like the issue lies within node_modules directory. Any help ...

Adjust the background color of a list item using Typescript

At the top of my page, there's a question followed by a list of answers and the option to add new ones. You can see an example in the image below. https://i.stack.imgur.com/NPVh7.jpg The format for each answer is "(username)'s response: at this ...

Struggling with getting render props to work in Next.js version 13

Looking to develop a custom component for Contentful's next 13 live preview feature in the app directory, I thought of creating a client component that can accept a data prop and ensure type safety by allowing a generic type to be passed down. Here is ...

Ion-List seamlessly integrates with both ion-tabs and ion-nav components, creating a cohesive and dynamic user interface

On my homepage, there is an ion-list. Sometimes (not every time), when I select an item in this list or navigate to the register page using "this.app.getRootNav().push("ClienteCadastroPage")", and then select an input in the registerPage or descriptionPage ...

Revamp the button's visual presentation when it is in an active state

Currently, I'm facing a challenge with altering the visual appearance of a button. Specifically, I want to make it resemble an arrow protruding from it, indicating that it is the active button. The button in question is enclosed within a card componen ...

Express not functioning properly with custom error handler

I'm facing an issue while trying to implement a custom error handler for my Express routes. Despite following the instructions in the documentation which recommend placing the custom handler at the end of the use chain, it seems that the default error ...

What is the method for obtaining the dynamic key of an object?

Is there a way for me to access the value of record.year dynamically? It seems like using record["year"] should give me the same result. I am trying to make my chart adaptable to different x-y axis configurations, which is why I am using fields[0] to retr ...

Error in AngularX TS: Trying to invoke a type that does not have a callable signature

Encountering an issue while working on a component, specifically during ng serve/build process. Please note that this error is different from any console errors, despite what some may think. The expected outcome is for the code to successfully build and ru ...

The conditional type in TypeScript is malfunctioning

Upon finishing an article discussing conditional types in TypeScript located at: I have attempted to implement a conditional type in the following function: function convertToIsoString<T extends number|undefined>( timestamp:T ): T extends number ...

Ways to categorize by a particular date

const vehicleDetails = [ { "record_id": "2ff8212f-5ec9-4453-b1f3-91840a3fb152", "status_date_activity": { "On Rent": 1662021991000 } }, { "record_id": "c8c1 ...

How to import a module from the root path using TypeScript in IntelliJ IDEA

Despite this topic being widely discussed, I still struggle to understand it. Below is my tsconfig.json file: { "compilerOptions": { "module": "commonjs", "target": "es2017", "sourceMap": true, "declaration": true, "allowSyntheticDe ...

What is the best way to eliminate a particular element from an array produced using the .map() function in

I am experiencing an issue with my EventCell.tsx component. When a user clicks on the component, an event is created by adding an element to the components state. Subsequently, a list of Event.tsx components is rendered using the .map() method. The problem ...