Encountering difficulty in retrieving properties from the parent class

Please take a look at the TypeScript snippet provided below:

class A {
  value = 20;
  func1(){
    console.log("parent > " + this.value);
  }
}
class B extends A {
  value = 10;
  func1(x?:number){
     console.log("child > " + this.value);
    super.func1();
  }
}
let C = new B();
C.func1();

After executing the compiled code in Chrome, it seems to output child = 10 and parent = 10 .

What is the correct method for accessing parent class properties from the child class as the keyword this does not appear to function properly.

Answer №1

Is there a proper way to access parent class properties from the parent class as using this does not seem to be effective?

This is set to reference the current instance. When trying to access this.a, it will point to the same value in both the parent and child classes. Basically, the property a gets overridden, so when the parent accesses this.a, it actually accesses the child property.

Furthermore

  • Parent methods can still be accessed through super even if they are overridden
  • Parent properties are permanently overridden

Documentation

https://basarat.gitbooks.io/typescript/docs/classes.html

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

Angular 2's ng-required directive is used to specify that

I have created a model-driven form in Angular 2, and I need one of the input fields to only show up if a specific checkbox is unchecked. I was able to achieve this using *ngIf directive. Now, my question is how can I make that input field required only whe ...

Error: Ionic 2 encountered an error: Highcharts has produced Error #17 - learn more at www.highcharts.com/errors/17

I'd like to incorporate a highchart gauge in my project, but I'm encountering an issue: Uncaught (in promise): Error: Highcharts error #17: www.highcharts.com/errors/17 error I've been advised to load the highcharts-more.js file, but I&a ...

What is the reason for not being able to use both the pattern attribute and formControl for the email field simultaneously?

I have set up an email form field with a RegEx check using the pattern attribute. <input matInput formControlName="email" name="email" pattern="^\w+([d\\+1\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" #input ...

Angular 6 implement a waiting function using the subscribe method

I need to make multiple calls to a service using forEach, where each call depends on the completion of the previous one. The code is as follows: itemDefaultConfiguration.command = (onclick) => { this.createConfiguration(configuration.components); ...

Using TypeScript to specify a limited set of required fields

Can a custom type constraint be created to ensure that a type includes certain non-optional keys from an object, but not all keys? For instance: class Bar { key1: number key2: Object key3: <another type> } const Y = { key1: 'foo' ...

Check if JSON is available and import it if it is present

I have a configuration file that varies depending on the environment, so I added it to my `.gitignore` file. In certain environments, the file may not exist at all. In such cases, default values will be used. Therefore, I am looking for a way to import a ...

An improved method for merging data from numerous RxJS observables

Within the ngOnInit() method, I am implementing the following: ngOnInit() { const exerciseObs = this.wodService.getAllExercises().pipe(take(1), map(data => { return {exercises: data}; })); const userObs = this.accountService.getAcco ...

Exploring Improved Methods for Implementing Nested Subscriptions in Typescript

In my Typescript code for Angular 11, I am working with two observables. The first one, getSelfPurchases(), returns data objects containing information like id, user_id, script_id, and pp_id. On the other hand, the second observable, getScriptDetails(32), ...

Emacs LSP reported that the server angular-ls:xxxxx/starting terminated with an exit status

Every time I try to open a new TypeScript file within my Angular project, I encounter an error message: The server angular-ls:xxxxx/starting has exited with status exit (please check the corresponding stderr for more details). Would you like to resta ...

What are the best practices for utilizing Angular form validation effectively?

I am currently working on implementing form validation in my project. I have created a basic login form and now I want to validate the input fields before submitting them to the server, while also providing visual feedback to the user if the inputs are inv ...

Manipulating and inserting objects into an array using React and Typescript with an undefined type

As I embark on my TypeScript journey in React, I decided to test my knowledge by creating a simple Todo App. Everything seems to be working fine except for one issue! After adding a new task and hovering over it, I received the following error message (tr ...

Retrieve an object containing properties specified in the function's parameter list

I am currently working on developing a function that can dynamically create and return an object with properties based on an array of strings provided as parameters. type Foods = 'apple' | 'banana' | 'pear'; function foodObje ...

Rect cannot be resized using mouse events

I am currently working on resizing the rectangle inside the SVG using mouse events. To achieve this, I have created another circle shape at the right bottom edge of the rectangle and implemented resize events on that shape. However, I'm facing an issu ...

Converting Angular HTTP Response from Object of Objects to Array with Interface Typing

After receiving a response, the data is structured as follows: { "0": { "name": "Novartis AG", "symbol": "NVS", "has_intraday": false, "has_eod": true ...

The return type of Array.find is accurate, however, it contains an error

Trying to find a way to indicate the expected return type of Array.find() in TypeScript, I encountered an incompatibility warning. View code in playground class A { "type"="A" t: string; #a = 0 constructor(t: string) { ...

How to open a PDF file in a new tab using Angular

Within my Angular 12 application, I am seeking to enable users to "view" a PDF file stored locally in the application within a new tab on Google Chrome. Currently, when implementing the code below in HTML, the file downloads rather than opening in a new ta ...

The argument specified as 'Blob | Blob[]' cannot be assigned to a parameter expecting just a 'Blob'

I've been working on this code snippet: const heicReader = new FileReader(); heicReader.onload = async () => { const heicImageString = heicReader.result; const { download_url } = await uploadPhotoToGcs({ ...

Importing ES6 modules in TypeScript using absolute paths

I've been on a quest for hours trying to figure out how to import local ES6 modules using an absolute path. Every time I attempt to import something in a module like : import { Module } from "src/my-module"; I keep getting the error "Error: Cannot f ...

Can someone explain how this "const s: string = ['a'][1];" is considered a valid Typescript expression?

I encountered an unexpected result when I executed the code const s: string = ['a'][1];. Instead of receiving a type error from the Typescript compiler, it returned undefined. This was surprising to me because I believed I was trying to assign an ...

React encountered an issue: each child element within a list must be assigned a unique "key" prop

I am feeling a bit puzzled as to why I keep getting the error message: child in a list should have a unique "key" prop. In my SearchFilterCategory component, I have made sure to add a key for each list item using a unique id. Can you help me figu ...