What is preventing me from accessing the properties of the parent abstract class?

Why am I encountering the error message "Abstract property 'field0' in class 'SuperAbstractClass' cannot be accessed in the constructor", even though upon inspecting the transpiled code, it appears that we do have access to this field? Alternatively, we could run it in the TypeScript playground to observe that field1 is set to "default value"

abstract class SuperAbstractClass {
    public abstract field0: string = 'default value';
    public abstract field1: string;
}

abstract class SubAbstractClass extends SuperAbstractClass {
    public field1: string = this.field0;
}

class SuboncreteClass extends SubAbstractClass {
    public field0: string = '';
}

var a = new SuboncreteClass()
console.log(a);

Transpiled

"use strict"; 
class SuperAbstractClass { 
    constructor() { 
        this.field0 = 'default value'; 
    } 
} 
class SubAbstractClass extends SuperAbstractClass { 
    constructor() { 
        super(...arguments); 
        this.field1 = this.field0; 
    } 
} 
class SuboncreteClass extends SubAbstractClass { 
    constructor() { 
        super(...arguments); 
        this.field0 = ''; 
    } 
} 
var a = new SuboncreteClass(); 
console.log(a);

Answer №1

I found this question intriguing as it led me to delve deeper into the concept at hand. It's quite surprising that initializing a property declared as abstract in the same class is actually allowed, as confirmed by microsoft/TypeScript#33356. While attempting to implement an abstract method in a similar manner would result in an error:

abstract class ImplAbstractMethod {
    abstract method() { } // error! 
    // Method 'method' cannot have an implementation because it is marked abstract
}

The intention behind marking a property as abstract and then providing a concrete value for it within the same class seems questionable, but ultimately it's your decision.


In reality, the initialization of the property serves as an internal aspect of the superclass and does not form part of its declaration. The formal declaration would look something like this:

declare abstract class DeclaredSuperAbstractClass {
    public abstract field0: string;
    public abstract field1: string;
}

It's not permissible to declare that an abstract class's property be initialized. Consequently, users of the superclass cannot assume that field0 has been initialized; they only recognize it as abstract, and therefore possibly non-existent. Hence the resulting error.


I keep circling back to the peculiar nature of initializing abstract properties. My suggestion would be that if you aim to enable subclasses to access a value set for field0 in the parent class, you should eliminate the abstract modifier from field0, given that it doesn't offer any clear benefit:

abstract class SuperAbstractClass {
    public field0: string = 'default value';
    public abstract field1: string;
}
abstract class SubAbstractClass extends SuperAbstractClass {
    public field1: string = this.field0; // okay
}

Playground link to code

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

Next.js React Hydration Issue - "Anticipated a corresponding <a> within the server HTML <a>"

Currently, I am encountering a hydration error while working on my Next.js project. The specific error message that keeps popping up is: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected serv ...

Why don't my absolute paths work on nested folders in React and Typescript?

Struggling to configure absolute paths in my React project, encountering challenges with nested folders and the use of @ prefix. Here's what I have set up in my tsconfig.json: { "compilerOptions":{ "baseUrl":"src", ...

I encountered a permission denied error while attempting to execute the command npm install -g tsc

My main objective is to convert TypeScript code to JavaScript. However, when I attempted to install the TypeScript compiler globally using 'npm install -g tsc', I encountered the following error: npm ERR! Error: EACCES: permission denied, rename ...

What is the specific category of Mongoose.startSession in the realm of Typescript?

In my Express/Typescript project with mongoose, I implemented a loader as follows: import mongoose from 'mongoose'; import { Db } from 'mongodb'; import config from '../config'; export default async (): Pr ...

How to upload files from various input fields using Angular 7

Currently, I am working with Angular 7 and typescript and have a question regarding file uploads from multiple input fields in HTML. Here is an example of what I am trying to achieve: <input type="file" (change)="handleFileInput($event.target.files)"&g ...

Tips for stopping </p> from breaking the line

<p>Available: </p><p style={{color:'green'}}>{props.active_count}</p><p>Unavailable: </p><p style={{color:'red'}}>{props.inactive_count}</p> https://i.sstatic.net/NQo5e.png I want the ou ...

Leveraging Angular 4 with Firebase to extract data from a database snapshot

My dilemma lies in retrieving data from a Firebase DB, as I seem to be facing difficulties. Specifically, the use of the "this" operator within the snapshot function is causing issues (highlighted by this.authState.prenom = snapshot.val().prenom) If I att ...

Navigating through complex routes was tricky in Next.js 14 due to the error 404 on hard navigation with

While working on implementing tab groups using Parallel Routes in Next.js 14, I encountered an issue where a 404 page only appears during hard navigation to /gnb/mypage/tab1. The tabs and their navigation function properly on initial render and when switch ...

Entering the appropriate value into an object's property accurately

I am currently facing an issue with typing the value needed to be inserted into an object's property. Please refer below. interface SliceStateType { TrptLimit: number; TrptOffset: number; someString: string; someBool:boolean; } inter ...

What is the best way to iterate over a proxy array in Vue?

Within the data() method, I have defined an array called exampleArray. When mounted(), a function is called to add elements to this array. Upon logging this.exampleArray, the result shows as a proxy object. In order to iterate through this array in anot ...

JavaScript code for when either "a," "b," or "c" is true, but not all of them

Hey there, I'm just getting started with JavaScript! I'm working on creating a syntax to determine if only one of three variables is present. if a and (not b or not c) or b and (not a or not c) or c and (not a or not b) ...

What is the best method for transferring chosen items to a different multiple select using Angular?

How can I transfer selected items to another list, in order to manipulate the final object/array later on? student.component.ts: students= []; studentsFinal = []; onGetStudents() { this.studentService.getStudents() .subscribe( (s ...

The variable isJoi has been set to true but there is an error due to an unexpected

I am currently developing a NestJs backend on multiple machines. One of the machines is experiencing issues with the @hapi/joi package. When running the NestJs application in development mode on this specific machine, I encounter the following error: PS C ...

What is the best way to arrange a list in Angular2 using AngularFire2's FirebaseListObservable?

Looking to retrieve all users from a Firebase realtime database and organize them based on a score property. I managed to achieve this by using the variable users: FirebaseListObservable<any[]>; however, encountered the following errors: Type & ...

In my Stripe application, I am looking to connect a single email address to a unique customer in order to prevent recurring payments from creating duplicate customer profiles. However, I am facing an issue where Stripe continues

My product is a subscription service that provides users with access to a specific service on my website. I have set up the product on Stripe and added the payment link to my website: <a className="bg-red-600 text-white py-2 px-4 rounded inline- ...

There seems to be an issue with functionality, as undefined is not behaving as expected in the combination of Graph

I am encountering an issue in my react native project where I am utilizing graphql codegen for generating types and hooks. The current version of react native that I am using is 0.74.5. However, I am facing an error which is preventing me from launching my ...

Is it possible to include a conditional type in TypeScript using inlining?

Apologies if this question seems basic to those well-versed in typesystems. I'm puzzled by the difference in outcomes when inlining a conditional statement in TypeScript. For instance, using the Extract conditional leads to different results dependin ...

Transferring information from ag-Grid to a different user interface

I have implemented ag-Grid to showcase some data and now I want this data to be transferred to another interface upon clicking a cell in the grid. To achieve this, I utilized the cellRendererFramework by creating a custom component called RouterLinkRendere ...

Tips for optimizing HttpRequests within nested for-loops that utilize subscribe()?

Our REST-API is designed to be frontend agnostic, meaning it always sends the IRI to nested resources. This results in multiple HTTP calls needed to retrieve data; first for the parent resource, then its child resources and so on. Each Country has linked E ...

How can Typescript elevate your use of the IFrame API?

Here is a code snippet that performs the following actions: let doc = this.iframe.contentDocument || this.iframe.contentWindow; let content = `...` doc!.open(); doc!.write(content); doc!.close(); Despite this, the Typescript linter thr ...