Modify visibility within a subclass

Is there a way to modify property visibility in a child class from protected to public? Consider the following code snippet:

class BaseFoo  {
    protected foo;
}

class Foo extends BaseFoo {
   foo = 1;
}

new Foo().foo;

It seems that this change is possible from protected to public, but not in any other direction. In fact, changing the visibility accidentally to public by omitting the modifier can be more harmful than attempting to change from protected to private (which is not allowed). What could explain this behavior? Is it a known issue?

Answer №1

After some careful consideration, it appears that the question has already been deliberated upon and subsequently closed as "working as intended" in the repository here. While my knowledge of OOP theory may be limited, I have come to understand the rationale behind the maintainer's perspective regarding the concept of protected methods within a class hierarchy.

class Foo extends BaseFoo {
   protected foo = 1;
}

This snippet illustrates how to maintain the privacy of the property foo within the child class Foo, while still allowing access to it from derived classes. As for the query regarding implicit property types (specifically, whether foo = 1 should default to public), it seems reasonable to expect such behavior. In TypeScript, defaulting to a public modifier is consistent across the language, and if there is a need to restrict this accessibility, one could employ the following approach:

class BaseFoo  {
    private foo;
}

class Foo extends BaseFoo {
   foo = 1; // results in a compiler error
}

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

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

How can we create a versatile Action type in typescript that can accommodate varying numbers of arguments and argument types?

When working with Typescript, encountering a duplicate type error can be frustrating. For instance, consider the following code snippet: export type Action<T> = (arg:T) => void export type Action<T1,T2> = (arg1:T1, arg2:T2) => void How c ...

Tips for effectively overriding a method in typescript

Why is this.fullName appearing empty in the show() method? class Person { protected name: string = ""; constructor(name: string) { this.makeSir(name); } makeSir(name: string) { this.name = "sir" + name; } } class M ...

Tips for hiding a sidebar by clicking away from it in JavaScript

My angular application for small devices has a working sidebar toggling feature, but I want the sidebar to close or hide when clicking anywhere on the page (i.e body). .component.html <nav class="sidebar sidebar-offcanvas active" id="sid ...

Module '. ' or its corresponding type declarations cannot be located

While working on my project with TypeScript and using Cheerio, I encountered an issue when trying to compile it with TSC. The compiler threw the following exception: error TS2307: Cannot find module '.' or its corresponding type declarations. 2 ...

The Child/Parent arguments in Typescript methods cannot be assigned

Why is this not working in TypeScript? class Parent { id: string = '' } class Child extends Parent{ name: string = '' } const fails: (created: Parent) => void = (created: Child) => { return }; const failsToo: ({ create ...

Creating an Observable from static data in Angular that resembles an HTTP request

I have a service with the following method: export class TestModelService { public testModel: TestModel; constructor( @Inject(Http) public http: Http) { } public fetchModel(uuid: string = undefined): Observable<string> { i ...

I'm curious if there's a method to ensure that the content within a mat-card stays responsive

So I'm working with this mat-card: <mat-card> <mat-card-content> <div *ngFor="let siteSource of siteSources | paginate: { itemsPerPage: 5, currentPage: page};"> <site-details [site]='siteSource'></s ...

Angular strictPropertyInitialization - best practices for initializing class members?

When initializing a component, I need to retrieve user information. However, with the Angular strict mode in place, I'm uncertain about where to fetch this data. I have considered 3 options. But which one is the most appropriate? Is there another alt ...

The requirement is for TypeScript to be cast as Partial<T>, with the condition that the keys

I'm currently looking for two different utility types: one that consists of a subset of a type with matching value types, and another that only requires the keys to exist in another type. I've devised the following solution, which appears to be ...

Vue is encountering difficulties resolving the index.vue file located in the parent directory

Having trouble importing a component from the path folder, I keep encountering an error message stating "Cannot find module './components/layout/Navbar'. Vetur(2307)". This is how I am attempting to import the component: import Navbar from "./c ...

Create a custom definition for the useSelector function within a separate TypeScript file in a React

Question: Is it possible to define a type like <TRootState, string> in an external file and use it directly inside multiple Component files? External file: export type TUser = <TRootState, string> // This method does not work Component's ...

Utilizing Angular's async pipe to dynamically customize and assign values to variables

I have a parent component named A with over 20 child components, all of which extend A and are located within <ng-content></ng-content>. Within component A, I am updating the value of the showContent variable in multiple places. The issue aris ...

The term "primordials is not defined" is a common error

Whenever I attempt to run Gulp using the task runner, I am encountering this error message. I suspect it may be due to updating my npm project, but I'm unsure about how to resolve it. Should I try installing a different version of npm? >Failed to r ...

Inserting items into an array entity

I am attempting to insert objects into an existing array only if a certain condition is met. Let me share the code snippet with you: RequestObj = [{ "parent1": { "ob1": value, "ob2": { "key1": value, "key2": va ...

Waiting for the response to come by subscribing in Angular

I am encountering an issue while trying to subscribe to an Observable and assign data from the response. The problem is that my code does not wait for the response before executing the console.log(this.newIds) line, resulting in an empty value being logg ...

The act of employing `Function.prototype.run` within an Angular TypeScript class is deemed as illegitimate

Is there a way to globally define a new function called run within my Angular component as shown below? Function.prototype.run = function (delay: number) { // some content; }; However, the compiler shows an error that the Property 'run' does n ...

Struggling to access the properties of a Material-UI Button

import * as React from "react"; import { styled } from "@mui/material/styles"; import MuiButton from "@mui/material/Button"; import Slider from "@mui/material/Slider"; interface Props { type: "primary" | ...

How can one retrieve the selected value from a dropdown menu in Angular?

Objective: My goal is to create a dropdown menu where users can select a value, which will then dynamically change the address of the website based on their selection. Issue: Although I managed to make the address change upon selection, it did so for ever ...

What are some strategies for enhancing TypeScript/Node speed in VSCode with the help of WSL2 and Docker?

My development environment consists of VSCode running on Windows (v1.58.2) with the Remote WSL extension (v0.58.2). I have Docker Desktop (3.5.2, engine: 20.10.7) set up to work with Linux containers through the WSL2 backend. Within these containers, I a ...