Implementing an Abstract Constructor in TypeScript's Abstract Class

Is it possible to develop an abstract constructor for an abstract class in TypeScript?

Let's consider the following abstract class as an example:

export abstract class Foo<T> extends Bar<T> {
  constructor(someParam: any) {
    super();
    this.someObj = someParam;
  }
}

This abstract class is then extended by the following class:

export class FooImpl extends Foo<SomeType> {
}

If the constructor is not overridden, the default parameterless constructor will be used in the FooImpl class, resulting in an incorrect state within the class.

How can we define an abstract constructor or compel consumers of the abstract class to override the constructor when consuming Foo<T>?

UPDATE

The specific code I have encountered is shown below and seems to be related to vscode:

export abstract class FireStoreDataSource<T> extends DataSource<T> {
  constructor(store: () => Observable<T[]>) {
    super();
  }
}

I am extending this class as follows:

export class AssessmentCenterDataSource extends FireStoreDataSource<AssessmentCenter> {
}

Then, creating an instance in an Angular component's ngOnInit:

ngOnInit() {
  this.dataSource = new AssessmentCenterDataSource(() => this.service.getData());
}

In vscode, I encounter a compiler error

[ts] Expected 0 arguments, but got 1.
. However, when I run ng build, it compiles correctly.

If I do not provide any arguments to the constructor, the compiler error disappears, but I receive an error when running ng build:

error TS2554: Expected 1 argument, but got 0.

It seems like this might be an issue with vscode or one of its extensions rather than TypeScript itself.

I am using vscode insiders version 1.26.0, TypeScript insiders version 3.0.1, and Angular 6.

Answer №1

In Typescript, if you do not override the constructor, it will be inherited from the base class.

For example, trying to create a new instance without passing required parameters would result in an error:

new FooImpl(); // error 

You must provide the necessary parameters when creating an instance:

new FooImpl("") //ok

Although there is no way to enforce the derived class to override the constructor specifically, inheriting the base constructor seems sufficient in most cases.

Playground link

Answer №2

Trying to instantiate a new object of FooImpl results in an error (if no arguments are passed to the constructor, as it is inherited), which then requires using the constructor with arguments:

const obj = new FooImpl();
You should provide 1 argument, but none were given.

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

Different or improved strategy for conditional rendering in Angular

Hey there! I've got a few *NgIf conditions in my template that determine which components (different types of forms) are displayed/rendered. For example, in one of my functions (shown below) private _onClick(cell:any){ this._enableView = fals ...

Having trouble implementing the latest Angular Library release

Just starting out with publishing Angular libraries, I've made my first attempt to publish a lib on NPM called wps-ng https://www.npmjs.com/package/wps-ng. You can check out my Public API file here https://github.com/singkara/wps-js-ng/blob/library_t ...

In TypeScript, this regular expression dialect does not permit the use of category shorthand

Recently, I attempted to implement a regular expression in TypeScript: I ran the following code: const pass = /^[\pL\pM\pN_-]+$/u.test(control.value) || !control.value; To my surprise, an error occurred: "Category shorthand not allowed in ...

Troubleshooting problem with TypeScript and finding/filtering operations

let access = environment.access.find(it => it.roleName == userRole); Property 'filter' does not exist on type '{ siteadmin: string[]; manager: string[]; employee: string[]; contractor: any[]; }'. This scenario should work perfectly ...

The typescript compiler encounters an error when processing code that includes a generator function

Recently, I started learning about TypeScript and came across the concept of generators. In order to experiment with them, I decided to test out the following code snippet: function* infiniteSequence() { var i = 0; while(true) { yield i++ ...

Custom Mapped Types in TypeScript

I'm currently exploring ways to create a custom type that will convert the properties of an object from type Vector to type Array. This is what I have so far type ToArray<T> = { [P in keyof T]: T[P] extends Vector<any> ? Array<any ...

Angular - Exploring the process of creating a secondary standalone build for a specific section of an application

I have created an Angular 4 (or 5) application with a specific structure as shown in the image below: https://i.sstatic.net/zK1BM.png Now, I need to develop a separate standalone angular application where only a selected group of Angular components from ...

Is it possible to pass a Styled Components Theme as Props to a Material UI element?

After spending 9 hours scouring the internet for a solution, I am at my wit's end as nothing seems to work. Currently, I am developing a React component using TypeScript. The issue lies with a simple use of the Material UI Accordion: const Accordion ...

Error: zsh is unable to locate the command, even after defining it in package.json bin and installing it globally

I attempted to create a command-line application using TypeScript. Below is the code I have written: //package.json { "name": "jihea-cli", "version": "1.0.0", "description": "", "main": "index.ts", "bin": { "cli": "./bin/index.ts" }, // ...

Update ngx-datatable when the user clicks on a different directive

My issue involves a Side Navigation with a docking feature and a data table in the Main View. When I undock the side navigation, the data table does not recalculate automatically, leaving empty space where the Side Navigation was. This requires me to manua ...

Tips for creating a cookie for an alternate website upon launching a new browser tab

Hey there, I'm facing an issue that I could really use some help with. To give you some context, I'm working on a project using Angular and TypeScript. My goal is to implement single sign-on functionality for multiple websites within one applica ...

Looking to execute multiple programs simultaneously within the prestart script in the package.json file, and bypass any exit error codes

I need to run yarn tsc and yarn lint during every yarn start to identify any code errors. This is how my scripts property is set up: "scripts": { "start": "expo start", "android": "expo start --android" ...

What steps do I need to take to create a pristine build of the Microsoft/VSCode source code?

Currently working on setting up a fresh development environment for microsoft/vscode. As a beginner in JS, TS, NPM, and Yarn, which specific command should I run in order to delete all build artifacts and output files and compile the code changes I made? ...

Currently, I am collaborating on an e-commerce endeavor utilizing TypeScript and sanity.io, encountering an issue along the way

Encountering an Uncaught TypeError message: Cannot read properties of undefined (reading '_ref'). While attempting to utilize code for displaying API content on a webpage, what might be causing this issue and how can it be resolved to successful ...

Acquire information from an Angular service and output it to the console

I am having trouble logging data from my service file in the app.component file. It keeps showing up as undefined. Below is the code snippet: service.ts getBillingCycles() { return this.http.get('../../assets/download_1.json'); }; app.com ...

Issue arises when compiling React Redux due to a union type that includes undefined

I am currently in the process of learning how to integrate Redux with React using Typescript. I encountered a compilation error that relates to the type of my store's state, specifically as {posts: PostType[]}. The error message states: Type '{ p ...

What benefits does Observable provide compared to a standard Array?

In my experience with Angular, I have utilized Observables in the state layer to manage and distribute app data across different components. I believed that by using observables, the data would automatically update in the template whenever it changed, elim ...

How can I suggest the return type of a function that is out of my control?

When I attempt to parse a JSON-formatted string, a linter error is triggered: let mqttMessage = JSON.parse(message.toString()) // ESLint: Unsafe assignment of an `any` value. (@typescript-eslint/no-unsafe-assignment) Given that I am in control of the con ...

Issue with TypeScript in Vue3: Unable to access computed property from another computed property

In my Vue3 project with TypeScript, I am encountering an issue where I am unable to access the properties of the returned JavaScript object from one computed property in another computed property using dot notation or named indexing. For instance, when tr ...

Merging an unspecified number of observables in Rxjs

My latest project involves creating a custom loader for @ngx-translate. The loader is designed to fetch multiple JSON translation files from a specific directory based on the chosen language. Currently, I am implementing file loading through an index.json ...