What is the reason that the protected keyword is not retained for abstract properties in TypeScript?

I'm uncertain whether this issue in TypeScript is a bug or intended functionality. In my Angular project, I have 3 classes - an abstract service, a service that implements the abstract service, and a component that utilizes the implementing service.

To simplify, the structure of my classes is as follows:

export abstract class BaseApiService {
  constructor() { }
  protected abstract baseUrl: string;
export class LogApiService extends BaseApiService {
  baseUrl = environment.apiBaseUrl;
  constructor() { }
}
export class LogPageComponent implements OnInit {

  constructor(private logApiService: LogApiService) { }

  ngOnInit(): void {
    this.logApiService.baseUrl = 'why can I change this?';
  }

}

By using the protected keyword on the baseUrl property in BaseApiService, one would expect the property to be mutable in LogApiService but immutable in LogPageComponent. However, this is not the case. The code in the ngOnInit function of LogPageComponent compiles and runs without any issues.
Adding the protected keyword within LogApiService can prevent LogPageComponent from altering LogApiService's baseUrl property like so:

protected baseUrl = environment.apiBaseUrl;
.

It seems like a potential oversight that the protected keyword needs to be added in both BaseApiService and LogPageComponent. Could this behavior be intentional, or should it be raised as a bug on Github in the TypeScript repository?

Answer №1

It is standard behavior to change the visibility of an inherited and protected member, resulting in the following:

// Here, the protected keyword is being removed and the field is made public
baseUrl = environment.apiBaseUrl;

You can modify a protected field to be public because using 'protected' allows a derived class to both read and write the field. The derived class can then decide whether to allow others to have access to it.

On the other hand, you cannot change a private field to be protected or public because there is no access to read or write that field.

UPDATE:

If you wish to avoid setting the 'protected' keyword repeatedly, simply refrain from overriding the field and directly manipulate it in the constructor as shown below:

export class LogApiService extends BaseApiService {
   // Do not override this => baseUrl = environment.apiBaseUrl;
  constructor() { 
   super();
   this.baseUrl = environment.apiBaseUrl;
 }
}

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

Tips for accessing the value stored within the parent element

As someone who is new to the world of javascript and typescript, I am currently working on an ionic application that involves fetching a list of values from a database. These values are then stored in an array, which is used to dynamically create ion-items ...

Incorporating regular expressions to extract a specific string from a URL is a requirement

Can anyone assist with extracting a specific string using regex in TypeScript? I have the following URL: https://test.io/content/storage/id/urn:aaid:sc:US:8eda16d4-baba-4c90-84ca-0f4c215358a1;revision=0?component_id=e62a5567-066d-452a-b147-19d909396132 I ...

I am unable to utilize the Web Share API for sharing a file within my React app written in TypeScript

Trying to launch a WebApp for sharing files has been quite a challenge. After some thorough research, I stumbled upon the Web Share API which seemed like the perfect solution based on standard practices. The documentation provided a clear outline of how it ...

Looking to resolve a module-specific error in Angular that has not been identified

While practicing Angular, I encountered an error during compilation: Module not found: Error: Can't resolve './app.component.css' in 'D:\hello-world-app\src\app' i 「wdm」: Failed to compile. This is my app.compo ...

Angular application table enclosed in a form, failing to capture checkbox values

I am working on an Angular 6 project and have a table with checkboxes. My goal is to select a row in the table by checking the checkbox, then click a "select" button to submit the data. However, my current HTML structure does not seem to be functioning as ...

Having trouble with React state not updating?

Hello, I am a beginner in the world of React and currently working on fetching an array of endpoints. My goal is to update the API's status every 15 seconds. Here is the code snippet for the array of endpoints: export const endpoints: string[] = [ " ...

When attempting to retrieve data from an API in Angular 8, I encountered difficulties in dynamically creating a formArray within a formArray

I am struggling to dynamically create form controls based on the data received, specifically for fields like task and template name. Your assistance is greatly appreciated. { "items": [ { "templatename": "Defult" ...

The GIPHY API object returns no results

Utilizing Angular 2 to fetch data from the GIPHY API. export class ListaGifsComponent { gifs : Object[] = []; urlBase = "http://api.giphy.com/v1/gifs/search?q="; termoPesquisado = "ryan+gosling"; key = "O8RhkTXfiSPmSCHosPAnhO70pdnHUiWn"; ...

What is the proper way to include special symbols such as "++" and "#" in a request?

I am facing an issue while trying to make a request to an ASP .NET CORE API from an Angular application using Typescript. Upon sending the request, the API searches in an SQL database for any rows with the specified value. The problem arises when attempt ...

Ways to verify the functionality of a function utilizing a Subscription that yields no return value

I'm working with a TypeScript ModelService that has an edit function: edit(model: Model): Observable<Model> { const body = JSON.stringify(model); return this.http.put(`/models/edit/${model.id}`, body)); } Additionally, there is a TypeScrip ...

Found a minor syntax problem in an Angular service related to error handling declaration

As I was working on customizing the Angular tutorial to fit my needs, I found myself wanting to merge the two error handler methods showcased in the tutorial into one. I appreciate the functionality of both methods and believe combining them will be benefi ...

Ngrx 8: Strategies for mocking various selectors with distinct return values

I am currently in the process of writing unit tests for an Angular 8 component that has a dependency on an ngrx store. I have multiple selectors set up within the ngOnInit function and I am looking to mock these selectors using the overrideSelector method. ...

esBuild failing to generate typescript declaration files while running in watch mode

Recently dove into using edBuild and I have to say, it's been a breeze to get up and running - simple, fast, and easy. When I execute my esBuild build command WITHOUT WATCH, I can see that the type files (.d.ts) are successfully generated. However, ...

Is it possible to generate a new array by combining the keys of one array object with the values of another array object?

I have a situation with two arrays set up like this arr1 = [ { 'name':'Victoria Cantrell', 'position':'Integer Corporation', 'office':'Croatia', 'ext' ...

Converting jQuery drag and drop functionality to Angular: A step-by-step guide

I have implemented drag and drop functionality using jquery and jquery-ui within an angular project. Below is the code structure: Index.html, <!doctype html> <html lang="en"> <head> <link href="//code.jquery.com/ui/1.10.3/themes/ ...

Is it possible to implement cross-field validation with Angular 2 using model-based addErrors?

Currently, I am working on implementing cross-field validation for two fields within a form using a reactive/model based approach. However, I am facing an issue regarding how to correctly add an error to the existing Error List of a form control. Form: ...

Setting up Webpack for react-pdf in a Next.js application

In my Next.js application, I am utilizing the react-pdf library to generate and handle PDF files on the client side without involving the server. However, I am facing challenges in setting up Webpack for Next.js as I lack sufficient expertise in this area. ...

Sending data to a React component from regular HTML

I have a question about implementing a method to pass custom attributes from HTML elements as props to React components. Here's an example: function someFunction(props) { return <h1>props.something</h1> } HTML: <div id="someEl ...

Learn the process of adjusting the Time Zone in Angular2-HighCharts!

I've been struggling for a few days now trying to adjust the UTC time in an area chart using Angular2-HighCharts. The backend API is returning timestamps which I then inject into the chart, but each time it's being converted to "human time" with ...

The NestJs project fails to display the updates when using the "tsc" command before running either "npm run start" or "npm run start:dev"

As a beginner in nestjs, I decided to start a tutorial to learn more about it. However, whenever I make updates or changes to my code, I don't see any changes reflected in the results. Can someone please assist me with this issue? Below are my tsconfi ...